don't dream your life, live your dreams !
Contents
If you use maven, add this to your pom.xml :
<!-- spring boot --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- jstl --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> </dependency> |
This file will tell spring what packages to scan:
@Configuration @ComponentScan(basePackages = "net.rabahi.spring") public class MainConfig { } |
This implementation replace the WEB-INF/web.xml file.
public class WebConfig extends AbstractAnnotationConfigDispatcherServletInitializer { /* (non-Javadoc) * @see org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer#getRootConfigClasses() */ @Override protected Class<?>[] getRootConfigClasses() { return new Class<?>[] { MainConfig.class, WebMvcConfig.class}; } /* (non-Javadoc) * @see org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer#getServletConfigClasses() */ @Override protected Class<?>[] getServletConfigClasses() { return null; } /* (non-Javadoc) * @see org.springframework.web.servlet.support.AbstractDispatcherServletInitializer#getServletMappings() */ @Override protected String[] getServletMappings() { return new String[] { "/" }; } /* (non-Javadoc) * @see org.springframework.web.servlet.support.AbstractDispatcherServletInitializer#getServletFilters() */ @Override protected Filter[] getServletFilters() { CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter(); characterEncodingFilter.setEncoding("UTF-8"); return new Filter[] { characterEncodingFilter}; } } |
@Configuration @EnableWebMvc public class WebMvcConfig extends WebMvcConfigurerAdapter { @Bean public ViewResolver viewResolver() { UrlBasedViewResolver viewResolver = new UrlBasedViewResolver(); viewResolver.setViewClass(JstlView.class); viewResolver.setPrefix("/WEB-INF/jsp/"); viewResolver.setSuffix(".jsp"); return viewResolver; } } |
When user request in the navbar ‘/helloworld’, the following method is fired:
@Controller @RequestMapping("/") public class HelloWorldController { @RequestMapping("/helloworld") public ModelAndView helloworld() { String message = "Hello world from spring controller !"; return new ModelAndView("helloworld", "message", message); } } |
It will request WEB-INF/jsp/helloworld.jsp (as describes in the WebConfig.java implementation).
To print the message “message”, we use ${message} in WEB-INF/jsp/helloworld.jsp :
message : ${message} |
Copyright © 2024 My linux world - by Marc RABAHI
Design by Marc RABAHI and encelades.
admin