【发布时间】:2012-10-31 07:29:35
【问题描述】:
我有一个使用过滤器 servlet 来创建会话的 Web 应用程序,但我遇到的会话问题如下:
url1: localhost:8080/home.html
url2: localhost:8080/user/1.html
如果用户首先访问url1,它将创建一个会话,如果用户导航到url2。它不会创建第二个会话。
但是如果用户首先访问url2,它将创建一个会话,如果用户导航到url2。它将创建第二个新会话。
这有什么问题?
如果用户首先访问url2,它看起来会为/ 创建一个JSESSIONID cookie,并为/user 创建另一个。
我的代码在这里:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
String errorMsg = null;
if (request instanceof HttpServletRequest && response instanceof HttpServletResponse)
{
final HttpServletRequest httpRequest = (HttpServletRequest) request;
final HttpServletResponse httpResponse = (HttpServletResponse) response;
httpRequest.setCharacterEncoding("UTF-8");
HttpSession httpSession = httpRequest.getSession(false);
String path = httpRequest.getServletPath();
if ("/login.htm".equals(path)){
String mail = httpRequest.getParameter("mail");
String password = httpRequest.getParameter("password");
if ((!Utils.isNull(mail)) && (!Utils.isNull(password)))
{
UserDTO dto = new UserDTO();
dto.setPassword(password);
dto.setMail(mail);
dto = is.loginValidate(dto);
if(dto!=null){
dto.setClientid(httpRequest.getHeader("User-Agent") + httpRequest.getRemoteAddr());
httpSession.setAttribute("system.userinfo", dto);
is.saveLastLoginDate(httpRequest);
}
}
}else{
if(httpSession==null){
httpSession = httpRequest.getSession(true);
}
Object obj = httpSession.getAttribute("system.userinfo");
if(obj==null){
UserDTO dto = new UserDTO();
dto.setUid(GUESTID);
dto.setClientid(httpRequest.getHeader("User-Agent") + httpRequest.getRemoteAddr());
httpSession.setAttribute("system.userinfo", dto);
}
}
【问题讨论】:
-
是的,我只是使用 HttpSession httpSession = httpRequest.getSession(false);要获取会话,如果会话为 null ,则使用以下命令创建它: if(httpSession==null){ httpSession = httpRequest.getSession(true); }
-
你能把你的过滤器的代码贴出来吗?
标签: java jakarta-ee servlets