是否可以通过应用程序获取 cookie 值?

Is it possible to get the cookie value over the application?

我有一个以前从未尝试过的不同要求。假设我有两个 Web 应用程序,它们将 运行 在同一浏览器上以 localhost 作为主机。是否可以在我的第一个 Web 应用程序中设置 cookie 值并在我的第二个 Web 应用程序中获取相应的 cookie 值?

如果可以,我该怎么做?

我尝试如下,但我得到的 Cookie 值为 null

在我的第一个 Web 应用程序中,

Cookie ck = new Cookie("PortalUser", uName);
ck.setDomain("localhost");
ck.setMaxAge(30 * 60);
response.addCookie(ck);

在我的第二个 Web 应用程序中,

HttpSession mySession = request.getSession();
System.out.println(mySession.getAttribute("PortalUser"));//Value is printing null

您可以尝试使用 CookieManager 并将其 Cookie 策略设置为 ACCEPT_ALL,然后使用 CookieHandler 获取 Cookie 商店。

CookieManager cookieManager = new CookieManager();
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(cookieManager);
// Creates url for the given string
URL url = null;
try {
    url = new URL("http://localhost/");
    // Opens a connection with the url specified and returns URLConnection object
    URLConnection urlConnection = url.openConnection();
    // Gets the contents from this url specifies
    urlConnection.getContent();
} catch (MalformedURLException | IOException e) {
    e.printStackTrace();
}
// Returns the cookie store(bunch of cookies)
CookieStore cookieStore = cookieManager.getCookieStore();
// Getting cookies which returns in the form of List of type HttpCookie
List<HttpCookie> listOfcookies = cookieStore.getCookies();
for (HttpCookie httpCookie: listOfcookies) {
    System.out.println("Cookie Name : " + httpCookie.getName() + " Cookie Value : " + httpCookie.getValue());
}