欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

springmvc实用篇 -- WebMvcConfigurer

程序员文章站 2022-03-18 13:55:32
...

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

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

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;
	}
}

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

 

一、addInterceptors

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

1.定义HandlerInterceptor

 public class MyInterceptor implements HandlerInterceptor{
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            System.out.println("preHandle:假设这里请求前进行判断是否有登陆");
            //假设这里请求前进行判断是否有登陆,有则return true,无则false
            return true;
        }

        @Override
        public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
            //请求中处理,也就是HandlerAdapter处理Handler后在返回视图前执行该方法
            System.out.println("postHandle==requestUrl:"+request.getRequestURI());
        }

        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
            //提交视图后执行该方法
            System.out.println("afterCompletion==requestUrl:"+request.getRequestURI());
        }
    }

2.定义WebMvcConfigurer添加addInterceptors

@Configuration
public class MyWebMvcConfigurer implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**").excludePathPatterns("/user/login");
    }
}

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

3.定义controller

@RestController
@RequestMapping("/user")
public class UserController {
    @RequestMapping("/login")
    public String index() {
        return "hello springmvc!login";
    }
    @RequestMapping("/get")
    public String get(){
        return "hello springmvc!get";
    }
}

4.执行结果

1)调用login方法:

springmvc实用篇 -- WebMvcConfigurer

springmvc实用篇 -- WebMvcConfigurer

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

2)请求get方法:

springmvc实用篇 -- WebMvcConfigurer

springmvc实用篇 -- WebMvcConfigurer

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

 

二、addArgumentResolvers

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

1.定义HandlerMethodArgumentResolver:

class MyHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {
        @Override
        public boolean supportsParameter(MethodParameter parameter) {
            return parameter.getParameterType().getName().equals(UserA.class.getName());//仅对UserA有效
        }

        @Override
        public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
            //模拟从session中获取登陆的用户信息
            Object attribute = webRequest.getAttribute("user", NativeWebRequest.SCOPE_SESSION);//Request中的用户属性
            //然后放入UserA的对象里
            //这里直接写死一个
            attribute = new UserA("sessionUserName", 20);
            return attribute;
        }
    }

2.定义WebMvcConfigurer添加addArgumentResolvers:

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

3.定义controller:

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

4.执行结果:

springmvc实用篇 -- WebMvcConfigurer

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

 

三、addResourceHandlers

静态资源访问

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

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

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

2.本地资源:

springmvc实用篇 -- WebMvcConfigurer

3.访问资源:

springmvc实用篇 -- WebMvcConfigurer

 

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