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.
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.
Thymeleaf view resolver works by surrounding the view name with a prefix and suffix. The default values of prefix and suffix are 'classpath:/templates/' and '. html', respectively. Spring Boot also provides an option to change the default value of prefix and suffix by setting spring.
The ViewResolver provides a mapping between view names and actual views. The View interface addresses the preparation of the request and hands the request over to one of the view technologies.
Spring MVC is a Web MVC Framework for building web applications. In generic all MVC frameworks provide a way of working with views. Spring does that via the ViewResolvers, which enables you to render models in the browser without tying the implementation to specific view technology.
The basic purpose of the @Controller annotation is to act as a stereotype for the annotated class, indicating its role. The dispatcher will scan such annotated classes for mapped methods, detecting @RequestMapping annotations (see the next section).
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; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With