【SpringBoot拦截器】

2022年05月13日 阅读数:4
这篇文章主要向大家介绍【SpringBoot拦截器】,主要内容包括基础应用、实用技巧、原理机制等方面,希望对大家有所帮助。

LoginIntercepter

@Slf4j
public class LoginIntercepter implements HandlerInterceptor {
   
   
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
   
   
        String requestURI = request.getRequestURI();
        log.info("拦截的请求路径是"+requestURI);
        HttpSession session = request.getSession();
        Object loginUser = session.getAttribute("loginUser");
        if (loginUser==null){
   
   
            //session.setAttribute("msg","请先登陆");
            request.setAttribute("msg","请先登陆");
            //response.sendRedirect("/");
            request.getRequestDispatcher("/").forward(request,response);
            return false;
        }else {
   
   
            return true;
        }
    }
}

implements WebMvcConfigurer

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

页面登陆逻辑

@Controller
public class IndexController {
   
   
//    //用于一访问当前项目路径就进入登录页面(index.html)
//    public String loginPage(){
   
   
//        return
//    }

    @PostMapping("/login")
    public String main(User user, HttpSession session, Model model){
   
   
        if (StringUtils.hasText(user.getUsername())&&"123456".equals(user.getPassword())){
   
   
            //把登录成功的用户保存起来
            session.setAttribute("loginUser",user.getUsername());
            //登录后重定向到main,防止表单重复提交
            return "redirect:/main";
        }else {
   
   
            model.addAttribute("msg","用户名或密码错误");
            //回到登录页面
            return "index";
        }

    }
    @RequestMapping("/main")
    public String mainPage(HttpSession session,Model model){
   
   
        return "dashboard";
    }
}