[英]Session variable not set in Spring
我有一个Spring控制器,它将一个变量放入会话中:
public class LoginFormController extends SimpleFormController {
public ModelAndView onSubmit(HttpServletRequest request,
HttpServletResponse response, Object command) throws Exception {
request.getSession().setAttribute("authenticated_user", "authenticated_user");
}
}
然后,我有了一个HandlerInterceptor。 在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;
}
问题在于,由于request.getSession()。getAttribute(“ authenticated_user”))始终解析为null,因此似乎未设置会话变量。
有什么想法吗?
谢谢,Krt_Malta
尝试throw new ModelAndViewDefiningException(new ModelAndView("logonPage"))
而不是return false
。
在您的logonPage中,将操作明确包含在form标签中,如下所示:
<form:form method="post" commandName="login" action="logonPage.htm">
您还可以注入ServletRequestAttributes。 通过包括:
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
我在抽象超级控制器中执行了此操作,因此我的所有控制器都可以识别servlet请求。
要提取您使用的Request对象,可以使用以下命令
protected ServletRequestAttributes getServletRequest(){
return (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.