栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot中写一个拦截器-以及写MVC相关组件的规则

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot中写一个拦截器-以及写MVC相关组件的规则

【1】在SpringBoot官方文档中有这么一段话

> If you want to keep Spring Boot MVC features and you want to add additional [MVC configuration](https://docs.spring.io/spring/docs/5.0.5.RELEASE/spring-framework-reference/web.html#mvc) (interceptors, formatters, view controllers, and other features), you can add your own `@Configuration` class of type `WebMvcConfigurer` but **without** `@EnableWebMvc`. If you wish to provide custom instances of `RequestMappingHandlerMapping`, `RequestMappingHandlerAdapter`, or `ExceptionHandlerExceptionResolver`, you can declare a `WebMvcRegistrationsAdapter` instance to provide such components.

> If you want to take complete control of Spring MVC, you can add your own `@Configuration` annotated with `@EnableWebMvc`.

翻译过来就是:

> 如果你想要保持Spring Boot 的一些默认MVC特征,同时又想自定义一些MVC配置(包括:拦截器,格式化器, 视图控制器、消息转换器 等等),你应该让一个类实现`WebMvcConfigurer`,并且添加`@Configuration`注解,但是**千万不要**加`@EnableWebMvc`注解。如果你想要自定义`HandlerMapping`、`HandlerAdapter`、`ExceptionResolver`等组件,你可以创建一个`WebMvcRegistrationsAdapter`实例 来提供以上组件。

> 如果你想要完全自定义SpringMVC,不保留SpringBoot提供的一切特征,你可以自己定义类并且添加`@Configuration`注解和`@EnableWebMvc`注解

【2】所以我们需要写一个带有@Configuration的类,并且这个类需要实现WebMvcConfigurer接口,并且重写里面的方法。

【2.1】这里我们就拿拦截器来举例,首先创建一个拦截器对象。

            加上Component注解,因为既然都用到SpringBoot了,再用new就有点low了

            这里大家可能会问,拦截器有啥用呢,其实拦截器可以在用户登陆的时候,来判断这个用户是否有某种权限,或者密码错误的情况下跳转到那个页面。例如我们已经把User信息存入到Session中,那么我们就可以在preHandle中获取User信息,然后和数据库中的信息进行匹对,然后选择返回true还是false,重定向等。

@Component
public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle method is running!");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle method is running!");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion method is running!");
    }
}

        写好了拦截类后,还需要一个实现了WebMvcConfigurer的类

        重写addInterceptors方法,里面添加我们写好的拦截器,还要添加拦截路径。

@Configuration
public class MvcConfiguration implements WebMvcConfigurer {

    @Autowired
    private HandlerInterceptor myInterceptor;

    
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(myInterceptor).addPathPatterns("/**");
    }
}

  

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/679131.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号