简体   繁体   English

未在Spring中设置会话变量

[英]Session variable not set in Spring

I have a Spring controller which is putting a variable in the session: 我有一个Spring控制器,它将一个变量放入会话中:

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. 然后,我有了一个HandlerInterceptor。 In the preHandle method, I check for the variable in the session: 在preHandle方法中,我在会话中检查变量:

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. 问题在于,由于request.getSession()。getAttribute(“ authenticated_user”))始终解析为null,因此似乎未设置会话变量。

Any ideas plz? 有什么想法吗?

Thanks, Krt_Malta 谢谢,Krt_Malta

Try throw new ModelAndViewDefiningException(new ModelAndView("logonPage")) instead of return false . 尝试throw new ModelAndViewDefiningException(new ModelAndView("logonPage"))而不是return false

And in your logonPage, explicitly include the action in the form tag, something like this: 在您的logonPage中,将操作明确包含在form标签中,如下所示:

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

You can also inject the ServletRequestAttributes. 您还可以注入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. 我在抽象超级控制器中执行了此操作,因此我的所有控制器都可以识别servlet请求。

To extract the Request object you use can use the following 要提取您使用的Request对象,可以使用以下命令

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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