You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Spring Boot+JPA中存储Teacher实体至HTTP Session实现登录权限控制

Spring Boot中登录后将Teacher实体存入HTTP Session并校验登录状态的实现

一、在登录接口中存入Teacher到HTTP Session

在validateLogin方法中注入HttpSession对象,登录验证通过后,将Teacher实体存入Session即可。

修改后的登录接口代码:

@PostMapping(value = "/validateLogin")
public ResponseEntity<Object> validateLogin(@RequestBody Map<String, String> user, HttpSession session) {
    try {
        Teacher t = teacherRepository.findUser(user.get("name"), user.get("email"));
        if (t != null && encoder.matches(user.get("password"), t.getPassword())) {
            // 将Teacher实体存入HTTP Session
            session.setAttribute("loggedInTeacher", t);
            return ResponseEntity.status(HttpStatus.OK)
                    .body(Map.of("result", "ok", "details", "login approved"));
        } else {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                    .body(Map.of("result", "error", "details", "login denied"));
        }
    } catch (Exception e) {
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(Map.of("result", "error", "details", e.getMessage()));
    }
}

二、在主页接口中校验Session中的登录状态

同样注入HttpSession对象,从Session中获取已登录的Teacher实例,判断用户是否处于登录状态。

修改后的主页接口代码:

@GetMapping("/mainPage")
public String mainPage(HttpSession session) {
    // 从Session中获取已登录的Teacher
    Teacher loggedInTeacher = (Teacher) session.getAttribute("loggedInTeacher");
    if (loggedInTeacher != null) {
        return "mainPage";
    } else {
        return "您未登录,请先登录!";
    }
}

关键说明

  • 你的Teacher实体已经实现了Serializable接口,这是对象存入HTTP Session的必要条件,确保实体可以被序列化存储,这部分无需修改。
  • 如果需要对多个接口统一做登录校验,推荐使用Spring拦截器(Interceptor)或Spring Security框架,避免在每个接口中重复编写校验逻辑。

内容的提问来源于stack exchange,提问作者Nikolas Trapp

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 04:33:43