Ravi Jain Ravi Jain - 19 days ago 6
Java Question

ViewResolver using Java annotation

Is it possible in Spring 3.1.1 to configure a view resolver using Java annotations?

I am done with all configurations using Java annotations, but I am stuck at view resolver.

Code



package com;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import javax.sql.DataSource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import com.*;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.UrlBasedViewResolver;
import org.springframework.web.servlet.view.JstlView;

@Configuration
@ComponentScan("com")
public class AppConfig
{
{
//Other bean declarations
}

@Bean
public UrlBasedViewResolver urlBasedViewResolver()
{
UrlBasedViewResolver res = new InternalResourceViewResolver();
res.setViewClass(JstlView.class);
res.setPrefix("/WEB-INF/");
res.setSuffix(".jsp");

return res;
}
}


I used this code and ran the application, but it's not returning the appropriate view. However, if I configure a viewresolver in the
app-servlet.xml
file, it works fine.

Answer

Your class should extend WebMvcConfigurerAdapter class. please have a look at below example

@Configuration
@ComponentScan(basePackages="com")
@EnableWebMvc
public class MvcConfiguration extends WebMvcConfigurerAdapter{

    @Bean
    public ViewResolver getViewResolver(){
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");
        return resolver;
    }
}