Spring MVC 系列:注解开发(SpringMVCConfig、SpringConfig、AbstractAnnotationConfigDispatcherServletInitializer详细配置)
使用配置类和注解代替web.xml和SpringMVC配置文件的功能
一、创建初始化类,代替web.xml
在Servlet3.0环境中,容器会在类路径中查找实现javax.servlet.ServletContainerInitializer接口的类,如果找到的话就用它来配置Servlet容器。 Spring提供了这个接口的实现,名为SpringServletContainerInitializer,这个类反过来又会查找实现WebApplicationInitializer的类并将配置的任务交给它们来完成。Spring3.2引入了一个便利的WebApplicationInitializer基础实现,名为AbstractAnnotationConfigDispatcherServletInitializer,当我们的类扩展了AbstractAnnotationConfigDispatcherServletInitializer并将其部署到Servlet3.0容器的时候,容器会自动发现它,并用它来配置Servlet上下文。
package com.mcode.api.config;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.filter.HiddenHttpMethodFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
import javax.servlet.Filter;
/**
* ClassName: WebInit
* Package: com.mcode.api.config
* Description:
*
* @Author robin
* @Create 2023/8/10 21:24
* @Version 1.0
*/
public class WebInit extends AbstractAnnotationConfigDispatcherServletInitializer {
/**
* 指定spring的配置类
* @return
*/
protected Class<?>[] getRootConfigClasses() {
return new Class[]{SpringConfig.class};
}
/**
* 指定SpringMVC的配置类
* @return
*/
protected Class<?>[] getServletConfigClasses() {
return new Class[]{SpringMVCConfig.class};
}
/**
* 指定DispatcherServlet的映射规则,即url-pattern
* @return
*/
protected String[] getServletMappings() {
return new String[]{"/"};
}
/**
* 注册过滤器
* @return
*/
@Override
protected Filter[] getServletFilters() {
CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter();
encodingFilter.setEncoding("UTF-8");
encodingFilter.setForceEncoding(true);
HiddenHttpMethodFilter hiddenHttpMethodFilter = new HiddenHttpMethodFilter();
return new Filter[] {hiddenHttpMethodFilter,encodingFilter};
}
}
二、创建SpringConfig配置类,代替Spring的配置文件
package com.mcode.api.config;
import org.springframework.context.annotation.Configuration;
/**
* ClassName: SpringConfig
* Package: com.mcode.api.config
* Description:
*
* @Author robin
* @Create 2023/8/10 21:25
* @Version 1.0
*/
@Configuration
public class SpringConfig {
//ssm整合之后,spring的配置信息写在此类中
}
三、创建SpringMVC配置类,代替SpringMVC的配置文件
package com.mcode.api.config;
import com.mcode.api.interceptors.FirstInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.*;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;
import org.thymeleaf.spring5.SpringTemplateEngine;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.ITemplateResolver;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;
import java.util.List;
import java.util.Properties;
/**
* ClassName: SpringMVCConfig
* Package: com.mcode.api.config
* Description:
*
* @Author robin
* @Create 2023/8/10 21:26
* @Version 1.0
*/
/**
* 代替SpringMVC的配置文件:
* 1、扫描组件 2、视图解析器 3、view-controller 4、default-servlet-handler
* 5、mvc注解驱动 6、文件上传解析器 7、异常处理 8、拦截器
*/
//将当前类标识为一个配置类
@Configuration
//1.扫描组件
@ComponentScan("com.mcode.api.controller")
//5.开启MVC注解驱动
@EnableWebMvc
public class SpringMVCConfig implements WebMvcConfigurer {
/**
* 使用默认的servlet处理静态资源
* 4、default-servlet-handler
* @param configurer
*/
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
/**
* 6.配置文件上传解析器
* @return
*/
@Bean
public CommonsMultipartResolver multipartResolver(){
return new CommonsMultipartResolver();
}
/**
* 8.配置拦截器
* @param registry
*/
public void addInterceptors(InterceptorRegistry registry) {
FirstInterceptor interceptor = new FirstInterceptor();
registry.addInterceptor(interceptor).addPathPatterns("/**");
}
/**
* 3.配置视图控制,view-controller
* @param registry
*/
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
}
/**
* 7、异常处理
* @param resolvers
*/
public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {
SimpleMappingExceptionResolver exceptionResolver = new SimpleMappingExceptionResolver();
Properties properties = new Properties();
properties.setProperty("java.lang.ArithmeticException", "error");
exceptionResolver.setExceptionMappings(properties);
exceptionResolver.setExceptionAttribute("ex");
resolvers.add(exceptionResolver);
}
/**
* 配置生成模板解析器
* @return
*/
@Bean
public ITemplateResolver templateResolver(){
WebApplicationContext context = ContextLoader.getCurrentWebApplicationContext();
ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(context.getServletContext());
templateResolver.setPrefix("/WEB-INF/templates/");
templateResolver.setSuffix(".html");
templateResolver.setCharacterEncoding("UTF-8");
templateResolver.setTemplateMode(TemplateMode.HTML);
return templateResolver;
}
/**
* 生成模板引擎并为模板引擎注入模板解析器
* @param templateResolver
* @return
*/
@Bean
public SpringTemplateEngine templateEngine(ITemplateResolver templateResolver){
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver);
return templateEngine;
}
/**
* /生成视图解析器并未解析器注入模板引擎
* @param templateEngine
* @return
*/
@Bean
public ViewResolver viewResolver(SpringTemplateEngine templateEngine){
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setCharacterEncoding("UTF-8");
viewResolver.setTemplateEngine(templateEngine);
return viewResolver;
}
}
四、测试功能
index.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>首页</title>
</head>
<body>
<h1>首页</h1>
<a th:href="@{/testAnnotation}">测试注解</a>
</body>
</html>
error.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>error</title>
</head>
<body>
<h1>错误页面</h1>
<p th:text="${ex}"></p>
</body>
</html>
success.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>success</title>
</head>
<body>
<h1>success</h1>
</body>
</html>
TestController
package com.mcode.api.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* ClassName: TestController
* Package: com.mcode.api.controller
* Description:
*
* @Author robin
* @Create 2023/8/10 21:23
* @Version 1.0
*/
@Controller
public class TestController {
@RequestMapping("/testAnnotation")
public String testAnnotation() {
System.out.println(1 / 0);
return "success";
}
}
FirstInterceptor
package com.mcode.api.interceptors;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* ClassName: FirstInterceptor
* Package: com.mcode.api.interceptors
* Description:
*
* @Author robin
* @Create 2023/8/10 21:35
* @Version 1.0
*/
public class FirstInterceptor implements HandlerInterceptor {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("FirstInterceptor.preHandle");
return true;
}
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("FirstInterceptor.postHandle");
}
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("FirstInterceptor.afterCompletion");
}
}
微信:17873041739