javaspringspring-mvcspring-validatorstruts-validation

Accessing session in Spring validate method


I am migrating my Struts application to Spring. While migrating I came across the validate method of Struts which needs to be migrated in Spring. The Struts validate method accepts parameters as ActionMapping mapping, HttpServletRequest req and using the req object session was created in validate method of Struts. But the validate method of Spring only accepts parameters: Object target, Errors errors . So how can I create a session object in the validate method of Spring ? Any kind of help is appreciated.

Thanks!


Solution

  • You can obtain the session by doing the following

    ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
    HttpSession session = attr.getRequest().getSession();
    

    I do agree with Prashant that a one for one migration might not be the best way forward but without more context its hard to say