springmvc 验证包含 userobject 的 httpsession

springmvc validate httpsession containing userobject

我需要以更好的方式为我当前的项目验证 HttpSession(针对 Spring MVC 应用程序)。

场景如下:

1) 成功验证用户后,userObject 对象将添加到 httpSession class

HttpSession session = req.getSession(true);
session.setAttribute(AppConstants.LOGGEDIN_PARAM, userDetail);

2) 然后对于每个请求,从 HttpSession Class 中检索 userObject 以验证用户 Session

@RequestMapping(value = "/apply", method = RequestMethod.GET)
public String getTourApplyPage(HttpServletRequest req, ModelMap map) {
    UserDetailTO userDetail = (UserDetailTO) req.getSession().getAttribute(AppConstants.LOGGEDIN_PARAM);
    Long employeeId = userDetail.getUserType() == 1 ? userDetail.getEmployeeId():userDetail.getUserId();
    if (employeeId == 0) {
        req.setAttribute(AppConstants.MSG_PARAM, "Invalid employee Id.");
        return userDetail.getUserType() == 1 ? AppConstants.PIS_MESSAGE : AppConstants.ADMIN_PIS_MESSAGE;
     }
     ...
}   

可以有更好的方法在 HttpSession 中设置 userDetail 对象,但我有一个限制,不能更改此实现(第 1 点)。

是否可以更改从 HttpSession 获取 userDetail 对象的更好实现(第 2 点)?

Is it possible to write a better implementation for getting a userDetail object from httpSession?

在如此高的抽象级别上工作,就像控制器所处的那样,您不一定需要注入 HttpServletRequestHttpSession

您可以使您的控制器具有会话范围,并在那里注入一个具有会话范围的 bean。该 bean 可以保存 userDetails 和验证失败的消息。

@RestController
@Scope("session")
public class Controller {

    @Autowired
    private SessionDetails details;

    @PostMapping(path = "/validate")
    public void validate() {
        details.setUserDetails(...);
    }

    @GetMapping(path = "/apply")
    public String apply() {
        final UserDetailTO userDetails = details.getUserDetails();
        ...
    }

}

@Component
@Scope("session")
class SessionDetails {
    private String message;
    private UserDetailTO userDetails;
    // getters & setters
}