SpringBoot 学习笔记心得拦截器配置使用

Posted Adorable_Rocy

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBoot 学习笔记心得拦截器配置使用相关的知识,希望对你有一定的参考价值。

1.配置拦截器的使用

1	实现HandlerInteceptor 接口 , 重写三个实现方法。
public class LoginInteceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
 
        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 {

    }
2.一般在这里处理登录逻辑,对请求进行拦截。在preHandle()方法中
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        log.info("拦截的路径为:{}",requestURI);
        Object user =  request.getSession().getAttribute("user");
        //是否登录
        log.info("user对象为:{}",user);
                if(user != null){
                    return true;
                }
                //转发
            request.setAttribute("msg","请先登录!");
            request.getRequestDispatcher("/login").forward(request,response);
        return false;
    }

2.配置类

2 配置类实现WebMvcConfigurer 接口,重写 void addInterceptors(InterceptorRegistry registry)  方法
@Configuration //配置类注解
public class LoginConfigrable implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInteceptor()) //将拦截器注册进来
                .addPathPatterns("/**")
                .excludePathPatterns("/","/login","/css/**","/js/**","/images/**","/fonts/**","/user/login");
    }
}

3.Controller类

1.表单访问请求
@PostMapping("/user/login")
    public String userLogin(@RequestParam("username") String username , @RequestParam("password") String password , Model model ,
                            HttpServletRequest httpServletRequest){
        if(loginService.checkLogin(username, password)){
                log.info("登录成功!!");
                User user = new User();
                user.setName(username);
                user.setPassword(password);
                httpServletRequest.getSession().setAttribute("user",user);
                return "redirect:/success.html"; //重定向到成功的界面
            }
              log.info("登录失败!!");
              model.addAttribute("msg","用户名或密码错误");
            return "login"; //失败重新转发回来
    }
2.只有当条件满足的时候才会被放行,否则直接被进行拦截。

在这里插入图片描述

以上是关于SpringBoot 学习笔记心得拦截器配置使用的主要内容,如果未能解决你的问题,请参考以下文章

SpringBoot 学习笔记心得自定义Starter启动器

B站学习springboot笔记

SpringBoot 学习笔记心得请求参数处理

SpringBoot 学习笔记心得单文件&多文件上传

spring security +MySQL + BCryptPasswordEncoder 单向加密验证 + 权限拦截 --- 心得

spring security +MySQL + BCryptPasswordEncoder 单向加密验证 + 权限拦截 --- 心得