Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

springmvc validate httpsession containing userobject

I need to validate HttpSession (for Spring MVC Application) in a better way for my current Project.

Here is the Scenario:

1) Once user is successfully validated, userObject object is added to httpSession class

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

2) Then for each request, userObject is retrieved from HttpSession Class to validate user 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;
     }
     ...
}   

There can be better approaches to set userDetail object inside HttpSession but I had a restriction to not change this implementation (Point 1).

Can it possible to change getting a better implementation for getting a userDetail object from HttpSession (Point 2)?

like image 848
Ankit Avatar asked Aug 15 '26 17:08

Ankit


1 Answers

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

Working at such a high level of abstraction, as controllers are at, you don't necessarily need to inject neither an HttpServletRequest nor an HttpSession.

You can make your controller session-scoped and inject a session-scoped bean there. The bean can hold a userDetails and a message for failed validations.

@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
}
like image 122
Andrew Tobilko Avatar answered Aug 18 '26 05:08

Andrew Tobilko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!