springmvc验证包含userobject的httpsession

时间:2017-12-14 12:37:48

标签: java spring spring-mvc httpsession session-management

我需要以更好的方式为我当前的Project验证HttpSession(对于Spring MVC Application)。

以下是场景:

1)成功验证用户后,HttpSession session = req.getSession(true); session.setAttribute(AppConstants.LOGGEDIN_PARAM, userDetail); 对象被添加到httpSession类

userObject

2)然后对于每个请求,从HttpSession类中检索@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; } ... } 以验证用户会话

userDetail

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

是否可以更改从HttpSession(第2点)获取while (more_to_read) { written = write(fd, ...); if (written == 0) { struct pollfd wait = { .fd = fd, .events = POLLOUT, .revents = 0 }; int status = poll(&wait, 1, TIMEOUT); // ... } // ... } 对象的更好实现?

1 个答案:

答案 0 :(得分:1)

  

是否可以编写更好的实现来从userDetail获取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
}