我有一个不同的要求,我以前没有尝试过。假设我有两个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
答案 0 :(得分:0)
您可以尝试使用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());
}