【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";
    }
}

你可能感兴趣的