简体   繁体   中英

Session variable not set in Spring

I have a Spring controller which is putting a variable in the session:

public class LoginFormController extends SimpleFormController {

    public ModelAndView onSubmit(HttpServletRequest request, 
            HttpServletResponse response, Object command) throws Exception {

            request.getSession().setAttribute("authenticated_user", "authenticated_user");
    }
}

I then have a HandlerInterceptor. In the preHandle method, I check for the variable in the session:

public boolean preHandle(HttpServletRequest request,
                                      HttpServletResponse response,
                                      Object handler) throws Exception {

        /* first, check if the requested view even required authentication */
        if (isAuthenticationRequired(request)) {

            /* check to see that user is logged in */
            if (null == request.getSession().getAttribute("authenticated_user")) {
                forwardToLogonPage(request, response);
                return false;
            }
            /* all is ok - pass the request on */
            return true;
        }
        /* all is ok - pass the request on */
        return true;
    }

The problem is it seems that the session variable is not being set since request.getSession().getAttribute("authenticated_user")) is always resolving to null.

Any ideas plz?

Thanks, Krt_Malta

Try throw new ModelAndViewDefiningException(new ModelAndView("logonPage")) instead of return false .

And in your logonPage, explicitly include the action in the form tag, something like this:

<form:form method="post" commandName="login" action="logonPage.htm">

You can also inject the ServletRequestAttributes. By including:

import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

I did this in an abstract super controller so all my controllers would be servlet request aware.

To extract the Request object you use can use the following

protected ServletRequestAttributes getServletRequest(){
    return (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM