解決方案是爲應用程序創建兩個單獨的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));
}
}
這是一張圖像,顯示兩個名爲'url'的cookie已經創建。顯示其中一個的細節。路徑是針對一個客戶的,內容具有通向特定客戶的路徑,並且是會話cookie。另一個是類似的,除了路徑是其他客戶。
我生成的Cookie的方式取決於應用程序的訪問方式。我使用了兩個不同的鏈接:
<a href="app/customer1/servlet">Cookie Customer 1</a><br>
<a href="app/customer2/servlet">Cookie Customer 2</a>
問題是,由Tomcat創建的會話Cookie並不尊重這一點,它總是以應用程序的上下文作爲路徑(即'/ app')創建。我希望由Tomcat設置的* Session Cookie *的行爲與您所描述的相同。 –