Tomcat - 自定义会话Cookie处理

时间:2016-02-04 17:55:50

标签: java session tomcat

我的问题如下:我们正在将我们的应用程序部署为Tomcat中的WebApp。但是,我们的软件能够以多租户模式运行,即由一个WebApp实例提供多个“客户端”(租户)。

网址看起来像这样(我们假设WebApp的上下文是/app

  • 对于客户客户1,将为网址/app/customer1/<path>
  • 投放数据
  • 对于客户端客户2,数据将是URL /app/customer2/<path>
  • 的服务器

到目前为止,除了会话管理之外,一切都按预期工作。我们想为两个不同的路径/app/customer1/app/customer2使用两个不同的 会话Cookie 。但是,问题是Tomcat 总是为WebApp的上下文路径/app创建会话Cookie ,之后无法更改。

有谁知道这个问题的解决方案?提前谢谢!

迈克尔

1 个答案:

答案 0 :(得分:1)

解决方案是为应用程序创建两个单独的url模式。

使用@WebServlet:

@WebServlet(
    urlPatterns={"/app/customer1/servlet", "/app/customer2/servlet"})

或者,使用web.xml

<servlet>
    <servlet-name>MyApp</servlet-name>
    <servlet-class>myPackage.myClass</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>MyApp</servlet-name>
    <url-pattern>/app/customer1/servlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>MyApp</servlet-name>
    <url-pattern>/app/customer2/servlet</url-pattern>
</servlet-mapping>

现在,当您创建cookie时,路径将默认为访问servlet的路径。每个客户只会获得其cookie。

Cookie cookie = new Cookie("color", "green");

这是一个显示和创建cookie的servlet。

@WebServlet(
    urlPatterns={"/app/customer1/servlet", "/app/customer2/servlet"})
public class CookieExample extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
          throws ServletException, IOException {
        String urlSaved = "No Saved URL";
        Cookie[] cookies = req.getCookies();
        for (Cookie aCookie : cookies) {
            if ("url".equals(aCookie.getName())) {
                urlSaved = aCookie.getValue();
            }
        }
        resp.getWriter().print("Saved url = " + urlSaved); 
        String path = req.getRequestURI().substring(
            req.getRequestURI().indexOf("/app")
        );
        resp.addCookie(new Cookie("url", path));
    }    

}

这是一张图片,显示两个名为&#39; url&#39;已创建。显示其中一个的详细信息。该路径适用于一个客户,内容具有指向特定客户的路径,并且它是会话cookie。另一个是相似的,除了路径是为另一个客户。

List of cookies showing two cookies

我生成cookie的方式取决于应用程序的访问方式。我使用了两个不同的链接:

    <a href="app/customer1/servlet">Cookie Customer 1</a><br>
    <a href="app/customer2/servlet">Cookie Customer 2</a>