Java OpenResty Spring Spring Boot MySQL Redis MongoDB PostgreSQL Linux Android Nginx 面试 算法 小程序 Arthas JVM juc AQS Docker DevOps


Spring Boot 使用 Session 管理登录状态和拦截请求

Spring Boot Java Session 大约 3026 字

登录接口

Controller参数中直接注入HttpSession

@PostMapping("/login")
public Result login(@Valid @RequestBody LoginQuery query, HttpSession session) {
    log.info("dashboard login username#{} password#{}", query.getUsername(), query.getPassword());
    SysUser sysUser = loginService.login(query);
    if (sysUser == null) {
        return Result.builder().code(-1).msg("用户名或密码错误").build();
    }
    setAttribute(session, sysUser.getUsername(), sysUser.getId(), sysUser.getFid());
    return Result.builder().build();
}

登录成功,调用sessionsetAttribute方法,保存相关属性。

private void setAttribute(HttpSession session, String username, Integer uid) {
    if (session == null) {
        log.warn("session is null, username#{}, uid#{}", username, uid);
    } else {
        session.setAttribute(Const.SESSION_USERNAME, username);
        session.setAttribute(Const.SESSION_UID, uid);
    }
}

添加拦截器

拦截器校验当前session是否为空,拦截未登录请求。

@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String reqPath = httpServletRequest.getServletPath();
        // 只有返回true才会继续向下执行,返回false取消当前请求
        HttpSession session = httpServletRequest.getSession();
        if (session == null || StringUtils.isEmpty(session.getAttribute(Const.SESSION_USERNAME))) {
            log.trace("access#{}, not logged in, return", reqPath);
            httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
    }
}

配置拦截器,不拦截登录接口和错误页。

@Configuration
public class InterceptorConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {// 登录校验
        List<String> excludePaths = Arrays.asList("/dashboard/login", "/dashboard/error");
        registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/dashboard/**").excludePathPatterns(excludePaths);
    }

}

退出接口

移除Session

@PostMapping("/logout")
public Result logout(HttpSession session) {
    removeAttribute(session);
    return Result.builder().build();
}

// 注销,移除session 属性
private void removeAttribute(HttpSession session) {
    if (session != null) {
        session.removeAttribute(Const.SESSION_USERNAME);
        session.removeAttribute(Const.SESSION_UID);
    }
}

其他接口

在其他接口中使用session中保存的值。

@PostMapping("/list")
public Result list(@Valid @RequestBody ListQuery query) {
    Integer uid = (Integer) session.getAttribute(Const.SESSION_UID);
    List<Test> tests = testService.getList(uid, query);
    return Result.builder().data(tests).build();
}
阅读 6153 · 发布于 2020-03-28

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb

扫描下方二维码关注公众号和小程序↓↓↓

扫描二维码关注我
昵称:
随便看看 换一批