我有一个以前从未尝试过的不同需求。假设我有两个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());
}