【问题标题】:How to handle servlet session for different url?如何处理不同 url 的 servlet 会话?
【发布时间】: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


【解决方案1】:

看来是环境问题,换个电脑问题就解决了

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-13
    • 2012-07-10
    • 2017-11-09
    • 1970-01-01
    • 2019-08-20
    • 2016-06-10
    • 1970-01-01
    • 2015-11-30
    相关资源
    最近更新 更多