SpringBoot 拦截器

SpringBoot 拦截器,第1张

SpringBoot 拦截器 设置一个登录检查拦截器 1.处理登录请求

登录成功后将用户存入session

    @ResponseBody
    @PostMapping("/login")
    public String login(User user, HttpServletRequest request) {
        HttpSession session = request.getSession();
        if(user.getUsername().equals("bob") && user.getPassword().equals("123")) {
            session.setAttribute("user",user);
            return "登录成功";
        } else {
            return "登录失败";
        }
    }
2.编写拦截器

检查session中用户是否为空,不为空放行,为空跳转到登录界面

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        System.out.println("请求的路径为:" + requestURI);
        HttpSession session = request.getSession();
        Object user = session.getAttribute("user");
        if(user != null) {
            return true;
        }
        request.setAttribute("msg","请先登录~");
        request.getRequestDispatcher("/").forward(request, response);
        return false;
    }

    @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 {

    }
}
3.将拦截器注入容器

注:服务器内部转发也会经过拦截器

@Configuration
public class AdminMvcConfiguration implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInterceptor())
                .addPathPatterns("
                .excludePathPatterns("/","/login","/res/**");
    }
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/4659290.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-06
下一篇 2022-11-06

发表评论

登录后才能评论

评论列表(0条)

保存