spring boot session 登陆及拦截

登陆

@PostMapping("/login-in")
    public String loginIn(HttpServletRequest request, RedirectAttributesModelMap model)
    {
        HttpSession session = request.getSession();
        String phone = request.getParameter("phone");
        String password = request.getParameter("password");

        User user = userService.getByPhone(phone);
        if (null == user) {
            model.addFlashAttribute("status", "用户不存在");
            return "redirect:/login";
        }
        String mdPassword = ToolUtils.md(password);
        if (!user.getPassword().equals(mdPassword)) {
            model.addFlashAttribute("status", "用户名或密码错误");
            return "redirect:/login";
        }
        session.setAttribute("userId", user.getId());
        session.setAttribute("userPhone", user.getPhone());
        return "redirect:/store";
    }

 

登陆拦截

@Component
public class StoreLoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        if (null == session.getAttribute("userPhone")) {
            response.sendRedirect("/");
            return false;
        }
        return true;
    }
}

 

配置登陆拦截

@Configuration
public class StoreLoginConfig implements WebMvcConfigurer {
    @Autowired
    StoreLoginInterceptor storeLoginInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(storeLoginInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns(
                        "/",
                        "/style.css",
                        "/layui/**",
                        "/backend/**",
                        "/login",
                        "/login-in",
                        "/register",
                        "/register-in",
                        "/logout"
                );
    }
}

 

你可能感兴趣的:(java,java,框架)