• springboot对拦截器的支持


    拦截器:Interceptor 在AOP(Aspect-Oriented Programming)中用于在某个方法或字段被访问之前,进行拦截然后在之前或之后加入某些操作。比如日志,安全等。一般拦截器方法都是通过动态代理的方式实现。可以通过它来进行权限验证,或者判断用户是否登陆,或者是像12306 判断当前时间是否是购票时间。

    package com.example.spingbootdemo1.listener;
    
    import org.springframework.web.servlet.HandlerInterceptor;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class LoginInterceptor implements HandlerInterceptor {
        @Override
        public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
            System.out.println("preHandle被调用");
            if(httpServletRequest.getSession().getAttribute("username")!=null&&"xiadewang".equals(httpServletRequest.getSession().getAttribute("username").toString())){
                return true;
            }else{
                httpServletResponse.sendRedirect("/login.html");
                return false;
            }
        }
    }

    让它进行配置进容器中,要求所在类实现WebMvcConfigurer接口,在实现里面的

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

    和过滤器的区别:

    最简单明了的区别就是过滤器可以修改request,而拦截器不能。过滤器就是筛选出你要的东西,比如requeset中你要的那部分拦截器在做安全方面用的比较多,比如终止一些流程。

  • 相关阅读:
    Live2D 看板娘
    Live2D 看板娘
    Live2D 看板娘
    Live2D 看板娘
    Live2D 看板娘
    Live2D 看板娘
    Live2D 看板娘
    Live2D 看板娘
    Bound mismatch: The typae CertificateDirectory is not a valid substitute for the bounded parameter <M extends Serializable>
    Duplicate property mapping of contactPhone found in
  • 原文地址:https://www.cnblogs.com/nyhhd/p/12684472.html
Copyright © 2020-2023  润新知