解决方案是为应用程序创建两个单独的 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>