1.介绍
WebMvcConfigurer配置类其实是
Spring
内部的一种配置方式,采用JavaBean
的形式来代替传统的xml
配置文件形式进行针对框架个性化定制,可以自定义一些Handler,Interceptor,ViewResolver,MessageConverter。基于java-based方式的spring mvc配置,需要创建一个配置类并实现**WebMvcConfigurer
** 接口;在Spring Boot 1.5版本都是靠重写WebMvcConfigurerAdapter的方法来添加自定义拦截器,消息转换器等。SpringBoot 2.0 后,该类被标记为@Deprecated(弃用)。官方推荐直接实现WebMvcConfigurer或者直接继承WebMvcConfigurationSupport,方式一实现WebMvcConfigurer接口(推荐),方式二继承WebMvcConfigurationSupport类,具体实现可看这篇文章。https://blog.csdn.net/fmwind/article/details/82832758
2.WebMvcConfigure常用接口
public interface WebMvcConfigurer {
default void configurePathMatch(PathMatchConfigurer configurer){}
default void configureContentNegotiation(ContentNegotiationConfigurer configurer) {}
default void configureAsyncSupport(AsyncSupportConfigurer configurer) {}
default void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer){}
default void addFormatters(FormatterRegistry registry) {}
//拦截器配置
default void addInterceptors(InterceptorRegistry registry) {}
//静态资源处理
default void addResourceHandlers(ResourceHandlerRegistry registry) {}
//跨域问题
default void addCorsMappings(CorsRegistry registry) {}
//视图跳转控制器
default void addViewControllers(ViewControllerRegistry registry) {}
//视图解析器
default void configureViewResolvers(ViewResolverRegistry registry) {}
default void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {}
default void addReturnValueHandlers(List<HandlerMethodReturnValueHandler> handlers) {}
default void configureMessageConverters(List<HttpMessageConverter<?>> converters) {}
default void extendMessageConverters(List<HttpMessageConverter<?>> converters) {}
default void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {}
default void extendHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {}
@Nullable
default Validator getValidator() {
return null;
}
@Nullable
default MessageCodesResolver getMessageCodesResolver() {
return null;
}
}
2.1 addViewControllers:页面跳转
以前写SpringMVC的时候,如果需要访问一个页面,必须要写Controller类,然后再写一个方法跳转到页面,感觉好麻烦,其实重写WebMvcConfigurer中的addViewControllers方法即可达到效果了
@Configuration
public class MyConfigure implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
WebMvcConfigurer.super.addViewControllers(registry);
registry.addViewController("/").setViewName("index");
}
}
此时访问http://localhost:8080/ 就会访问到index.html
值的指出的是,在这里重写addViewControllers方法,并不会覆盖WebMvcAutoConfiguration中的addViewControllers(在此方法中,Spring Boot将“/”映射至index.html),这也就意味着我们自己的配置和Spring Boot的自动配置同时有效,这也是我们推荐添加自己的MVC配置的方式。
2.2 addInterceptors:拦截器配置
- addInterceptor:需要一个实现HandlerInterceptor接口的拦截器实例
- addPathPatterns:用于设置拦截器的过滤路径规则;
addPathPatterns("/**")
对所有请求都拦截 - excludePathPatterns:用于设置不需要拦截的过滤规则
- 拦截器主要用途:进行用户登录状态的拦截,日志的拦截等。
1.创建自己的拦截器类,并实现HandlerInterceptor接口
public class LoginHandlerInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
Object user = request.getSession().getAttribute("loginUser");
if(user == null){
//未登陆,返回登陆页面
request.setAttribute("msg","没有权限请先登陆");
request.getRequestDispatcher("/index.html").forward(request,response);
return false;
}else{
//已登陆,放行请求
return true;
}
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
2.实现WebMvcConfigurer接口中的addInterceptors方法把自定义的拦截器类添加进来即可
@Configuration
public class MyWebMvcConfig implements WebMvcConfigurer {
/**
* 添加拦截器
* @param registry
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
InterceptorRegistration interceptorRegistration = registry.addInterceptor(new LoginHandlerInterceptor());
interceptorRegistration.excludePathPatterns("/asserts/**","/error/**","/index.html","/","/user/login");
interceptorRegistration.addPathPatterns("/**");
}
}
2.3 addResourceHandlers:自定义资源映射
- addResourceLocations指的是文件放置的目录
- addResoureHandler指的是对外暴露的访问路径
比如,我们想自定义静态资源映射目录的话,只需重写addResourceHandlers方法即可。
@Configuration
public class MyWebMvcConfigurerAdapter implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/my/**").addResourceLocations("classpath:/my/");
}
}
通过addResourceHandler添加映射路径,然后通过addResourceLocations来指定路径。我们访问自定义my文件夹中的elephant.jpg 图片的地址为 http://localhost:8080/my/elephant.jpg
如果你想指定外部的目录也很简单,直接addResourceLocations指定即可,代码如下:
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/my/**").addResourceLocations("file:E:/my/");
}
2.4 configureViewResolvers视图解析器
这个方法是用来配置视图解析器的,该方法的参数ViewResolverRegistry 是一个注册器,用来注册你想自定义的视图解析器等。ViewResolverRegistry 常用的几个方法:https://blog.csdn.net/fmwind/article/details/81235401
/**
* 配置请求视图映射
* @return
*/
@Bean
public InternalResourceViewResolver resourceViewResolver()
{
InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver();
//请求视图文件的前缀地址
internalResourceViewResolver.setPrefix("/WEB-INF/jsp/");
//请求视图文件的后缀
internalResourceViewResolver.setSuffix(".jsp");
return internalResourceViewResolver;
}
/**
* 视图配置
* @param registry
*/
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
super.configureViewResolvers(registry);
registry.viewResolver(resourceViewResolver());
/*registry.jsp("/WEB-INF/jsp/",".jsp");*/
}
2.5 configureContentNegotiation:配置内容裁决的一些参数
2.6 addCorsMappings:跨域
2.7 configureMessageConverters:信息转换器
参考