飞道的博客

springmvc实用篇 -- WebMvcConfigurer

286人阅读  评论(0)

WebMvcConfigurer这个接口干什么用,文字上的描述我就不再说了,我们直接从功能入手就知道这玩意能帮我们做些什么事

首先我们打开这个接口所定义的哪些方法


  
  1. public interface WebMvcConfigurer {
  2. default void configurePathMatch(PathMatchConfigurer configurer) {}
  3. default void configureContentNegotiation(ContentNegotiationConfigurer configurer) {}
  4. default void configureAsyncSupport(AsyncSupportConfigurer configurer) {}
  5. default void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {}
  6. default void addFormatters(FormatterRegistry registry) {}
  7. default void addInterceptors(InterceptorRegistry registry) {}
  8. default void addResourceHandlers(ResourceHandlerRegistry registry) {}
  9. default void addCorsMappings(CorsRegistry registry) {}
  10. default void addViewControllers(ViewControllerRegistry registry) {}
  11. default void configureViewResolvers(ViewResolverRegistry registry) {}
  12. default void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {}
  13. default void addReturnValueHandlers(List<HandlerMethodReturnValueHandler> handlers) {}
  14. default void configureMessageConverters(List<HttpMessageConverter<?>> converters) {}
  15. default void extendMessageConverters(List<HttpMessageConverter<?>> converters) {}
  16. default void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {}
  17. default void extendHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {}
  18. @Nullable
  19. default Validator getValidator() {
  20. return null;
  21. }
  22. @Nullable
  23. default MessageCodesResolver getMessageCodesResolver() {
  24. return null;
  25. }
  26. }

这里面吧定义了N多个方法供我们自定义添加配置,其中这里我就挑几个比较常用的来示范下它的用途

 

一、addInterceptors

从名字上看我们就可以猜到是添加自定义拦截器的,下面来示范下

1.定义HandlerInterceptor


  
  1. public class MyInterceptor implements HandlerInterceptor{
  2. @Override
  3. public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
  4. System.out.println( "preHandle:假设这里请求前进行判断是否有登陆");
  5. //假设这里请求前进行判断是否有登陆,有则return true,无则false
  6. return true;
  7. }
  8. @Override
  9. public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
  10. //请求中处理,也就是HandlerAdapter处理Handler后在返回视图前执行该方法
  11. System.out.println( "postHandle==requestUrl:"+request.getRequestURI());
  12. }
  13. @Override
  14. public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
  15. //提交视图后执行该方法
  16. System.out.println( "afterCompletion==requestUrl:"+request.getRequestURI());
  17. }
  18. }

2.定义WebMvcConfigurer添加addInterceptors


  
  1. @Configuration
  2. public class MyWebMvcConfigurer implements WebMvcConfigurer {
  3. @Override
  4. public void addInterceptors(InterceptorRegistry registry) {
  5. registry.addInterceptor( new MyInterceptor()).addPathPatterns( "/**").excludePathPatterns( "/user/login");
  6. }
  7. }

.addPathPatterns("/**")表示拦截所有请求;.excludePathPatterns("/user/login")表示不拦截该请求

3.定义controller


  
  1. @RestController
  2. @RequestMapping( "/user")
  3. public class UserController {
  4. @RequestMapping( "/login")
  5. public String index() {
  6. return "hello springmvc!login";
  7. }
  8. @RequestMapping( "/get")
  9. public String get(){
  10. return "hello springmvc!get";
  11. }
  12. }

4.执行结果

1)调用login方法:

因为是login故这里是不会进拦截,所以就不会打印任何东西

2)请求get方法:

这里进了拦截器所以会进行打印操作

 

二、addArgumentResolvers

从方法参数上可以猜测到添加自定义HandlerMethodArgumentResolver参数解析,下面我们来操作看下

1.定义HandlerMethodArgumentResolver:


  
  1. class MyHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {
  2. @Override
  3. public boolean supportsParameter(MethodParameter parameter) {
  4. return parameter.getParameterType().getName().equals(UserA.class.getName()); //仅对UserA有效
  5. }
  6. @Override
  7. public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
  8. //模拟从session中获取登陆的用户信息
  9. Object attribute = webRequest.getAttribute( "user", NativeWebRequest.SCOPE_SESSION); //Request中的用户属性
  10. //然后放入UserA的对象里
  11. //这里直接写死一个
  12. attribute = new UserA( "sessionUserName", 20);
  13. return attribute;
  14. }
  15. }

2.定义WebMvcConfigurer添加addArgumentResolvers:


  
  1. @Override
  2. public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
  3. resolvers.add( new MyHandlerMethodArgumentResolver());
  4. }

3.定义controller:


  
  1. @RequestMapping( "/index")
  2. public String index(UserA userA){
  3. return "hello springmvc!userA:"+userA;
  4. }

4.执行结果:

这里能看取到在resolveArgument赋值的userA

 

三、addResourceHandlers

静态资源访问

1.我们直接重写addResourceHandlers方法:


  
  1. @Configuration
  2. public class MyWebMvcConfigurer implements WebMvcConfigurer {
  3. @Override
  4. public void addResourceHandlers(ResourceHandlerRegistry registry) {
  5. registry.addResourceHandler( "/file/**").addResourceLocations( "classpath:/static/", "file:D:/tomcat/");
  6. }
  7. }

addResourceHandler("/file/**")添加对外访问路径,addResourceLocations添加本地目录资源路径

2.本地资源:

3.访问资源:

 

ok.其他的方法我就不再尝试了,网上资料一大堆,主要这里是记录下有这么个配置类叫做WebMvcConfigurer,他非常好用


转载:https://blog.csdn.net/u011320740/article/details/105495831
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场