Replace the functionality of web.xml and SpringMVC configuration files with configuration classes and annotations.
Create an initialization class
In the Servlet3.0 environment, the container will be in the classpath lookup javax.mail. Servlet. ServletContainerInitializer interface classes, if found, you can use it to configure the servlet container.
Spring provides the implementation of this interface, called SpringServletContainerInitializer, this class, in turn, will find implementation WebApplicationInitializer classes and the configuration tasks to them.
Spring3.2 based implementation, introduces a convenient WebApplicationInitializer called AbstractAnnotationConfigDispatcherServletInitializer, When our class extends the AbstractAnnotationConfigDispatcherServletInitializer and deploy it to Servlet3.0 container, the container automatically discover it, and use it to configure the Servlet context.
Here’s a new project to demonstrate.
The dependencies in POM.xml can replicate the previous content, and web.xml and SpringMVC no longer need to be created.
package com.pingguo.mvc.config; import org.springframework.web.filter.CharacterEncodingFilter; import org.springframework.web.filter.HiddenHttpMethodFilter; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; import javax.servlet.Filter; Public class WebInit extends AbstractAnnotationConfigDispatcherServletInitializer {/ * * * specified spring configuration class * @ return * / @Override protected Class<? >[] getRootConfigClasses() { return new Class[]{SpringConfig.class}; } /** * specify SpringMVC configuration Class * @return */ @override protected Class<? >[] getServletConfigClasses() { return new Class[]{WebConfig.class}; } /** * specify a mapping rule for DispatcherServlet, [] getServletMappings() {return new String[]{"/"}; } @override protected Filter[] getServletFilters() {CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter(); encodingFilter.setEncoding("UTF-8"); encodingFilter.setForceRequestEncoding(true); HiddenHttpMethodFilter hiddenHttpMethodFilter = new HiddenHttpMethodFilter(); return new Filter[]{encodingFilter, hiddenHttpMethodFilter}; }}Copy the code
In the initialization class, you need to specify the spring Configuration class, SpringMVC Configuration class, to create the class, remember to annotate @Configuration, marked as the Configuration class.
In fact, the contents of the various configuration files are transferred to the configuration class, which will be initialized when the project starts. In addition, you return arrays, so you can return multiple configurations from each class.
Spring configuration classes
When using SSM integration, spring configuration information is written in the Spring configuration class, which is not needed here.
package com.pingguo.mvc.config;
import org.springframework.context.annotation.Configuration;
@Configuration
public class SpringConfig {
}
Copy the code
3. WebConfig configuration class
This configuration class replaces the contents of the previous springMVC. XML configuration file:
- Scan components
- View parser
- view-controller
- default-servlet-handler
- MVC annotation driver
- File upload resolver
- Exception handling
- The interceptor
@componentScan ("com.pingguo.mvc") @enableWebMvc public class WebConfig { @bean public ITemplateResolver templateResolver() {WebApplicationContext WebApplicationContext = ContextLoader.getCurrentWebApplicationContext(); / / ServletContextTemplateResolver need a ServletContext as structure parameters, Is obtained by the method of WebApplicationContext ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver ( webApplicationContext.getServletContext()); templateResolver.setPrefix("/WEB-INF/templates/"); templateResolver.setSuffix(".html"); templateResolver.setCharacterEncoding("UTF-8"); templateResolver.setTemplateMode(TemplateMode.HTML); return templateResolver; @bean public SpringTemplateEngine templateEngine(ITemplateResolver templateResolver) { SpringTemplateEngine templateEngine = new SpringTemplateEngine(); templateEngine.setTemplateResolver(templateResolver); return templateEngine; @bean public ViewResolver ViewResolver (SpringTemplateEngine templateEngine) { ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); viewResolver.setCharacterEncoding("UTF-8"); viewResolver.setTemplateEngine(templateEngine); return viewResolver; }}Copy the code
With these, you can test out the index page by writing the page and the Controller class.
<! DOCTYPE HTML > < HTML lang="en" XMLNS :th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>index </title> </head> <body> <h1>Copy the code
Controller:
@Controller public class TestController { @RequestMapping("/") public String index() { return "index"; }}Copy the code
Set deployment, start can open the home page.
The remaining configuration
Next, we need the WebConfig class to implement an interface, WebMvcConfigurer, to override the methods inside.
Configure the default servlet — handler
@enableWebMVC public class WebConfig implements WebMvcConfigurer {// Use the default servlet to process the static resource default-servlet-handler public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { configurer.enable(); }... .Copy the code
Configuring interceptors
Keep increasing.
. . Public void addInterceptors(InterceptorRegistry registry) {TestInterceptor firstInterceptor = new TestInterceptor(); registry.addInterceptor(firstInterceptor).addPathPatterns("/**"); }... .Copy the code
The interceptor will be created as before, and TestInterceptor is created here:
public class TestInterceptor implements HandlerInterceptor {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
return true;
}
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
Copy the code
Configure the view – controller
You can use this configuration when doing view jumps only.
Public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/").setViewName("index"); }Copy the code
Configuration file upload parser
. . @bean public MultipartResolver MultipartResolver (){CommonsMultipartResolver CommonsMultipartResolver = new CommonsMultipartResolver(); return commonsMultipartResolver; }... .Copy the code
Configuration Exception Handling
/ / configuration exception mapping public void configureHandlerExceptionResolvers (List < HandlerExceptionResolver > resolvers) { SimpleMappingExceptionResolver exceptionResolver = new SimpleMappingExceptionResolver(); Properties prop = new Properties(); prop.setProperty("java.lang.ArithmeticException", "error"); / / set the anomaly map exceptionResolver. SetExceptionMappings (prop); / / set Shared anomaly information of key exceptionResolver setExceptionAttribute (" ex "); resolvers.add(exceptionResolver); }Copy the code
The function inside is the same as before using the configuration file to achieve, you can test one by one.