Not able to get cookie in different context - java

i am setting cookie in context A and trying to get in context B in same domain . I am writing this code ....
Cookie cook= new Cookie("Name","value");
cook.setPath("/");
cook.setDomain(".foo.com");
response.addCookie(cook);
what is wrong here ? This is how i am getting the cookie in another context ..please note that my code is working fine in same context
Cookie cookie = null;
Cookie[] cookies = null;
cookies = request.getCookies();
out.println(cookies);
for (int i = 0; i < cookies.length; i++){
cookie = cookies[i];
if("Name".equals(cookie.getName( ))){
out.println("Name : " + cookie.getName( ) + ", ");
out.println("Value: " + cookie.getValue( )+" <br/>");
}}

Try to give the cookie a lifetime.
cookie.setMaxAge(86400) // 24h
A cookie without lifetime is bound to the browsing session. You might be in a different session when browsing in a different context.

Related

Can't find cookie if path is set to /

Currently using Java I am able to create a cookie and later retrieve it via Cookie[] browserCookies = request.getCookies();
The issue comes when I try create a cookie and set its path with cookie.setPath("/"); I can no longer find it later when the below code. It has a max age of 30 days so I know it's there and I see it get created but I can't find it any longer after that initial creation.
Here's what I have now which works when not setting a path to "/":
Look for a cookie with a specific name:
Cookie[] browserCookies = request.getCookies();
boolean foundCookie = false;
if (browserCookies != null) {
for (int i =0; i< browserCookies.length; i++) {
if ("foo".equalsIgnoreCase(browserCookies[i].getName())) {
foundCookie = true;
}
}
}
based on foundCookie, I do something but also based on that I create a new cookie if not found:
if (!foundCookie) {
Cookie fooCookie = new Cookie ("foo", "barValue");
fooCookie.setMaxAge(30 * 86400);
//fooCookie.setPath("/"); // If I set this, I can no longer find it later by the name
response.addCookie(fooCookie);
}
Thank you for any help

Will tomcat return session in case of multiple cookies exist with name JSessionIDs

Consider a situation where tomcat server receives multiple cookies with name JSessionID out of which one JSessionID is valid, so tomcat will still return a session or not? If tomcat reads only first JSessionID and maps with stored sessions then it may not find valid sesison and may store null. But if tomcat reads all cookies with name JSessionID and checks for existence of session against each JSessionID then it will return valid session. Sometimes we have observed that browser sends two cookies with same name one which is recently authentication session and one some old cookie with stale value. Hence the query to know how tomcat behaves?
From the code in tomcat source, a jsessionid cookie will override a jsessionid in the query (provided the context allow to use cookie for session tracking).
If multiple jsessionid cookies are present the first one representing a valid session (for the considered context) will be taken.
see Tomcat 7.0.x CoyoteAdapter class :
/**
* Parse session id in URL.
*/
protected void parseSessionCookiesId(org.apache.coyote.Request req, Request request) {
// If session tracking via cookies has been disabled for the current
// context, don't go looking for a session ID in a cookie as a cookie
// from a parent context with a session ID may be present which would
// overwrite the valid session ID encoded in the URL
Context context = (Context) request.getMappingData().context;
if (context != null && !context.getServletContext()
.getEffectiveSessionTrackingModes().contains(
SessionTrackingMode.COOKIE)) {
return;
}
// Parse session id from cookies
Cookies serverCookies = req.getCookies();
int count = serverCookies.getCookieCount();
if (count <= 0) {
return;
}
String sessionCookieName = SessionConfig.getSessionCookieName(context);
for (int i = 0; i < count; i++) {
ServerCookie scookie = serverCookies.getCookie(i);
if (scookie.getName().equals(sessionCookieName)) {
// Override anything requested in the URL
if (!request.isRequestedSessionIdFromCookie()) {
// Accept only the first session id cookie
convertMB(scookie.getValue());
request.setRequestedSessionId
(scookie.getValue().toString());
request.setRequestedSessionCookie(true);
request.setRequestedSessionURL(false);
if (log.isDebugEnabled()) {
log.debug(" Requested cookie session id is " +
request.getRequestedSessionId());
}
} else {
if (!request.isRequestedSessionIdValid()) {
// Replace the session id until one is valid
convertMB(scookie.getValue());
request.setRequestedSessionId
(scookie.getValue().toString());
}
}
}
}
}

Delete a cookie by its value

How do I delete a cookie by its value?
In my.jsp page I am setting the cookie
String timeStamp = new SimpleDateFormat("dd:MM:yyyy_HH:mm:ss:SSS").format(Calendar.getInstance().getTime());
timeStamp = timeStamp + ":" + System.nanoTime();
String loc = "/u/poolla/workspace/FirstServlet/WebContent/WEB-INF/"+timeStamp;
Cookie cookie = new Cookie("path", loc);
Multiple users will have cookies with the same name but different loc values,
So, How do I get the cookie value in servlet.java and delete a particular loca value cookie??
Cookies are not same for each user. Generally cookies are tied to the client/user/browser which is accessing the JSP/application and each client can have a cookie value of its own.
When you delete a cookie you just delete it for the client which has made the request to your application. Rest of the clients will still have their own cookie without any effect in the value. Hence, you need not to worry about deleting a cookie may affect multiple users.
In order to delete a cookie, first get all the cookies from request and delete the cookie which has particular name/value.
public void delete(MyType instance) {
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals("test")) {
cookie.setValue(null);
cookie.setMaxAge(0);
cookie.setPath(theSamePathAsYouUsedBeforeIfAny);
response.addCookie(cookie);
}
}
}
}
You will need to call getCookies() on the request and loop through them until you find the one you're looking for.
here is a little simple example tha might help you
//declaring a cookie
Cookie cookie = new Cookie(name, value);
//getting the cookie name
String name = cookie.getName()
//getting the cookie value
String value= cookie.getValue();

How to get asp.net created cookies in Java servlet?

How to get ASP.NET created cookies in a Java servlet?
This is My Cookie In ASP.NET
emid=11&eud=11&euid=33zU4Yq/p3k=&euseremail=F/zVoXtd4NoAd7yj6Z47gxFVaMCMYha/La6IzlC+xQo=&euserid=33zU4Yq/p3k=&emdn=testing
But when I try To Call it in Servlet it only prints: emid [only print the starting string before first equal to (=) sign]
I'm using the following code in Servlet to print cookies..
Cookie cookie = null;
Cookie[] cookies = null;
cookies = request.getCookies();
if( cookies != null ){
out.println("<h2> Found Cookies Name and Value</h2>");
for (int I = 0; I < cookies.length; I++){
cookie = cookies[I];
out.print("Name : " + cookie.getName( ) + ", ");
out.print("Value: " + cookie.getValue( )+" \n");
}
}else{
out.println(
"<h2>No cookies founds</h2>");
}
Whats wrong with my code?
The equals character is a reserved character in a cookie value. The specification compliant way of fixing this is to quote the cookie value by surrounding it with double quotes. However, some browsers don't handle this very well. If you are using Tomcat you can set the system property -Dorg.apache.tomcat.util.http.ServerCookie.ALLOW_EQUALS_IN_VALUE=true to allow equals in cookie values.

How can i get session id in java

I want to build an api in java to solve the security image problem occurred while moving one page to another page in any website. How can i get the session id and cookies so that i can post it with the security image string.
Thanks
Following should give session id in jsp
If you have EL enabled in your container, you can do it without the JSTL tag - ie just
<c:out value="${pageContext.session.id}"/>
or An alternative for containers without EL:
<%= session.getId() %>
Example to get Cookies is as :
<%
String cookieName = "username";
Cookie cookies [] = request.getCookies ();
Cookie myCookie = null;
if (cookies != null){
for (int i = 0; i < cookies.length; i++) {
if (cookies [i].getName().equals (cookieName)){
myCookie = cookies[i];
break;
}
}
}
%>
Referenced from: http://www.roseindia.net/jsp/jspcookies.shtml

Categories

Resources