I got a different requirement which I haven't tried before. Let's say I have two web applications which will run on same browser with localhost as a host. Can it possible to set the cookie value in my first web application and get the respective cookie value in my second web application?
If possible, How can I do the same?
I tried as follows, But I am getting Cookie
value as null
.
In my First Web application,
Cookie ck = new Cookie("PortalUser", uName);
ck.setDomain("localhost");
ck.setMaxAge(30 * 60);
response.addCookie(ck);
In my Second Web application,
HttpSession mySession = request.getSession();
System.out.println(mySession.getAttribute("PortalUser"));//Value is printing null
You can try using CookieManager
and set its Cookie Policy to ACCEPT_ALL
and then use CookieHandler
to get the Cookie
store.
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());
}