简体   繁体   中英

How to handle servlet session for different url?

I have a web application which uses a filter servlet to create session, but I have such problem with session as below:

url1: localhost:8080/home.html

url2: localhost:8080/user/1.html

If the user access the url1 first, it will create a session, and if user navigation to url2 . it will not create second session.

But if user access the url2 first, it will create a session, and if user navigation to url2 . it will create second new session.

What's wrong with it?

It looks it creates one JSESSIONID cookie for / and another for /user if user access url2 first.

My code is here:

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);
      }
  }

看来这是环境问题,如果我换了另一台电脑,问题就消失了

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