我有一个使用过滤器 servlet 来创建会话的 Web 应用程序,但我遇到的会话问题如下:
url1: localhost:8080/home.html
url2: localhost:8080/user/1.html
如果用户访问第url1
一个,它将创建一个会话,如果用户导航到url2
. 它不会创建第二个会话。
但是如果用户url2
首先访问,它将创建一个会话,如果用户导航到url2
. 它将创建第二个新会话。
它出什么问题了?
如果用户首先访问,它看起来会创建一个 JSESSIONID cookie/
和另一个。/user
url2
我的代码在这里:
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);
}
}