使用配置类和注解代替web.xml和SpringMVC配置文件的功能
在Servlet3.0环境中,容器会在类路径中查找实现javax.servlet.ServletContainerInitializer接口的类,如果找到的话就用它来配置Servlet容器。 Spring提供了这个接口的实现,名为SpringServletContainerInitializer,这个类又会查找实现WebApplicationInitializer的类并将配置的任务交给它们来完成。Spring3.2引入了一个便利的WebApplicationInitializer基础实现,名为AbstractAnnotationConfigDispatcherServletInitializer,当我们的类扩展了AbstractAnnotationConfigDispatcherServletInitializer并将其部署到Servlet3.0容器的时候,容器会自动发现它,并用它来配置Servlet上下文。
意思就是容器会自动发现继承了AbstractAnnotationConfigDispatcherServletInitializer的子类,并用它来配置servlet上下文。(用来代替web.xml)
package com.hxut.rj1192.annoation;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.filter.HiddenHttpMethodFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
import javax.servlet.Filter;
//代替web.xml filter过滤器 spring springmvc的配置类 dispracture的映射路径
public class webXml extends AbstractAnnotationConfigDispatcherServletInitializer {
// 指定spring配置类
@Override
protected Class>[] getRootConfigClasses() {
return new Class[] {SpringConfig.class};
}
// 指定springmvc配置类
@Override
protected Class>[] getServletConfigClasses() {
return new Class[]{SpringMvcConfig.class};
}
// 指定dispracture的映射路径 即url-pattern
@Override
protected String[] 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};
}
}
Spring-mvc配置文件(不管是xml还是注解的类)有如下八个功能
1视图解析器
2.扫描包的范围(组件扫描)
3.view-controller(只返回视图的控制方法)
4.defalut-servlet-handler 静态资源处理
5 mvc注解驱动
6.文件上传解析器
7.异常处理
8.拦截器
package com.hxut.rj1192.annoation;
import com.hxut.rj1192.InterceptorRegistry01;
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.HandlerInterceptor;
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;
//1视图解析器 2扫描包的范围(组件扫描) 3view-controller(只返回视图的控制方法) 4defalut-servlet-handler 静态资源处理和
//5 mvc注解驱动 6文件上传解析器 7异常处理 8拦截器
//代替springmvc的配置文件
//扫描包的范围(组件扫描)
@ComponentScan("com.hxut.rj1192")
//开启MVC注解驱动
@EnableWebMvc
@Configuration
public class SpringMvcConfig implements WebMvcConfigurer {
//配置视图解析器
// 这个注解是将类放进ioc容器中 因为web.xml中就是嵌套的,
@Bean
public ITemplateResolver templateResolver() {
WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
// ServletContextTemplateResolver需要一个ServletContext作为构造参数,可通过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;
}
//default-servlet configuure
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
WebMvcConfigurer.super.configureDefaultServletHandling(configurer);
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
InterceptorRegistry01 interceptorRegistry=new InterceptorRegistry01();
// addPathPatterns("/");是设置拦截的url
// excludePathPatterns(); 是设置不拦截的url
registry.addInterceptor(interceptorRegistry).addPathPatterns("/");
}
//视图控制器
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/hello").setViewName("succes");
}
//配置文件上传解析器
@Bean
public CommonsMultipartResolver multipartResolver(){
CommonsMultipartResolver commonsMultipartResolver=new CommonsMultipartResolver();
return commonsMultipartResolver;
}
//配置异常映射
@Override
public void configureHandlerExceptionResolvers(List resolvers) {
SimpleMappingExceptionResolver exceptionResolver = new SimpleMappingExceptionResolver();
Properties prop = new Properties();
prop.setProperty("java.lang.ArithmeticException", "error");
//设置异常映射
exceptionResolver.setExceptionMappings(prop);
//设置共享异常信息的键
exceptionResolver.setExceptionAttribute("ex");
resolvers.add(exceptionResolver);
}
}
全用xml写:
error
error
拦截器文件
package com.hxut.rj1192;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class InterceptorRegistry01 implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("prehandle 执行");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("posthandle 执行");
HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("afterhandle 执行");
HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
}
}