I know how to pass the jsessionid to the URL. I encode the url, which will look like this:
mysite.com;jsessionid=0123456789ABCDEF (http)
Does there exist a built-in method to retrieve the jsessionid from the URL, using Java? I found this method in the javadocs, isRequestedSessionIdFromURL, but it doesn't help me actually retrieve the value. Do I have to build my own retrieval method?
Thank you.
JSP has an implicit session object, similar the request object. It is an instance of java.servlet.http.HttpSession, which has the method getId().
So, you should be able to just do session.getId() in your JSP page.
Cookieless sessions are achieved in Java by appending a string of the format ;jsessionid=SESSION_IDENTIFIER to the end of a URL. To do this, all links emitted by your website need to be passed through either HttpServletRequest.encodeURL(), either directly or through mechanisms such as the JSTL tag. Failure to do this for even a single link can result in your users losing their session forever.
session.getId() should be able to get you the session id. WLS would be doing the actual parsing of the URl to retrieve the session id once it identifies that the session id is not stored in the cookie or in hidden form fields. The sequence usually is Cookie - URL - Hidden Form Fields.
Related
I was given this as an in class problem and recievd 0 as the result, but I can't find the fault with it. The questions is Write the lines of code you would need to use in a servlet to retrieve a parameter
from an incoming request and add it to the session as an attribute:
My answer:
String param1= request.getParameter("param1");
HttpSession session= request.getSession();
String parameter1= (String)request.getAttribute("param1");
session.setAttribute("param1", parameter1);
Also, is the '(String)' necessary in the second line? or just good practice?
Thanks :)
You've made a very common mistake, confusing attributes with parameters. In your code you have:
String parameter1= (String)request.getAttribute("param1");
Attributes can be thought of as meta-data of the request. For example, if the request is made via SSL then you can get data about the request from the attributes. Take a look at the documentation for getAttribute for more details.
Parameters, on the other hand, can be used to get URL parameters. Your last question actually points you in the correct direction - getParameter() already returns a String so you don't need to cast it.
Properly written the line above should be:
String parameter1= request.getParameter("param1");
getParameter() - used to get url parameter from request in server side(java side).
Where as If you want to fetch any values from java side to jsp(view side)
you can use setAttribute() in Server side(Java side) and get the value using getAttribute() from jsp.
I have a java web application. I implemented a login system, with user rights a while ago, and included a "remember-me" functionality with unique string ID's saved client side in cookies.
This has worked ok, except for the fact that the remember me functionality always fails on first page load whenever a new session starts. However, since most users access a non-restricted page first, complaints has been absent. Nonetheless, I'd like to fix it. Here is what I have learned.
I use implementations of javax.servlet.Filter to check if a user has rights to se a page. for example baseURL/pages/admin/*. Filter interface has a method called doFilter, which accepts a ServletRequest, and ServletResponse object as parameters. I cast these to HttpServletRequest and HttpServletResponse. The HttpServletRequest gives me access to cookies and session.
If i iterate through the cookies, I find my "remember"-cookie, with the unique ID as a value. However, this ID is wrong.
Now, in my Servlet class, which follows the front controller pattern, I also have a check for user logged in, and remember me. But because this is executed after the filter, it is not sufficient to check only here. Still, I do want to check for every page, even if it is not restricted, as it changes the layout slightly if you are logged in.
The java HttpServlet service method accepts a HttpServletRequest and HttpServletResponse object. In other words, no need for casting here. Funny thing is though, If i try to access my cookies from here, it will give me an identical id for the session cookie, but a completely different uid for my "remember"-cookie.
I have found that my system adds new remember cookies for each of my filters. And if I try to access a page in the admin path, both cookies from /webapp/pages, and cookie from /webapp/pages/admin will be present in chrome inspector. When accessing the cookies in the filter, the /webapp/pages/admin is the only one that will exist. Oppositely, the /webapp/pages is the only one that will exist in the front controller servlet service method.
I guess this is because of the mapping of said filter and servlet, which matches the path of the cookie. The problem is that I never intended there to be cookies stored hierarchically, and only want the one to be stored, at /webapp/pages. My system has now stored plenty of these deeper pathed cookies all over my client network, and whenever a user logs in and out, they might get out of sync with a new uid.
Is there a way I can force retrieving the /webapp/pages cookie over the /webapp/pages/admin cookie? Or is there a way to retrieve both? I could just check both uid's for a match if I can manage that (hence the title of my question)
For the future, I have made sure to set the path of cookie storage, so that the same path will be used, but as the cookies has a year to expire, this will not solve my problems for a long time, unless I find a way to check the correct cookie.
The answer to the title question is; you can't.
The browser will decide which cookies it deems most relevant, and there is nothing you can do to change that. When your filter is mapped to a subpath, and servlet is mapped to a higher path, you will get the best matching cookie for each path.
The specific problem in the question text is caused by a bad coding pattern. The remember me cookies should be stored at a specific path when created, in this case /webapp/pages. This will prevent the cookie from being created as multiples, in hierarchical paths.
There is still the problem of already existing cookies client side. These can be handled by adding the following javascript in a central area of your code, somewhere where you'd know that all users will encounter it:
document.cookie = 'remember=; path=/webapp/pages/user; expires=' + new Date(0).toUTCString();
document.cookie = 'remember=; path=/webapp/pages/admin; expires=' + new Date(0).toUTCString();
This will set the unwanted cookies to expire at an already past date, effectively deleting it.
Now only one cookie with name "remember" will exist for the domain, and both servlet and filters will fetch the same cookie, regardless of their mapped subpaths.
I have a legacy Java 1.6 running localhost with Tomcat 7 application using JSP pages, a frameset with frames, javascript, but no framework like Struts. I pass an object to display in the page from the servlet using the request or session and that works fine.
However, I made some changes recently and now I can't retrieve that same object back from the session or request. It had been working fine previously, so I'm not sure what is broken, but I can't even send a string value back from the JSP's back to the servlet.
I created a new stripped down JSP and I can't get anything back from that either using the request or session. It does the same thing when I push the code our Tomcat 6 web server. Using the debugger, I see the objects populated in the session, but then lost later when a new session is created each time as in using this simple code to get the sessionid:
System.out.println("The session id is: " + session.getId());
The session id is: EB431C19B41957B2BB2EFC3DBAF32241
The session id is: C9CBD30E84D5C93DF6114C1412AE5523
I then see this in firebug under the Header, response headers:
Set-Cookie JSESSIONID=C9CBD30E84D5C93DF6114C1412AE5523; Path=/Name omitted here/; HttpOnly,
so I know cookies are set. I also removed jquery and I"m stripping down the jsp code as much as possible, but that doesn't seem to be the issue.
I'm using:
HttpSession session = request.getSession(true); but using false didn't matter.
session.setAttribute("ObjNameList", objNameList);
The context.xml has cookies set to true and we do use response.sendRedirect, but only if an error is thrown as in: response.sendRedirect("Error.jsp"); There is no place in the code with session invalidate either.
All I'm doing from the jsp is sending a form back using something like:
document.formName.submit(); which works fine. Using this code to try and set a simple string in the session doesn't work either:
session.setAttribute("somevalue","someValue");
Gives me null in the servlet here:
String val = (String) session.getAttribute("somevalue");
Any ideas as to what could be causing this?
Resultion:
It turned out to be an issue with the url, a typo actually, as BalusC mentioned, so the path for the session cookies didn't match between the jsp and the servlet.
Doublecheck if the request URL to that servlet matches the session cookie domain and path. If it doesn't match, then the browser simply won't send the session cookie back along with the request and the server will think that there's no means of an established session and will therefore simply create a new one.
You can check cookies in the HTTP traffic monitor of browser's web developer toolset (press F12 in Chrome/Firefox23+/IE9+ and open "Network" tab). When a new session starts, the server must have returned a response with Set-Cookie header with therein the cookie value and path (and implicitly domain). When the browser sends a subsequent request on the same domain and path, then it must have passed that cookie back via Cookie request header.
See also:
How do servlets work? Instantiation, sessions, shared variables and multithreading
I have a cookie that is formatted like partA:partB. The colon is not escaped in any fashion. I need to read this cookie in a JSP script, and request.getCookies() is only returning partA. I can't change the cookie because it is used in multiple applications, and fixing the cookie would break production code. Any ideas how I can read the full value of this cookie?
You should be able to read the Cookie header directly using the HttpServletRequest.
it seems that the Parameter-Name in the GET request, that represents the SessionID (like jsessionid=XXXXXXXXXXXXXXXXXXXXXXXXXX in Tomcat) is not standardized in the servlet-spec? How can I get the (Servelt Container Specific) name of the SessionID? (At least in Websphere there seems to be the possibilty to change the name of the SessionID-Parameter-Name)
=> The underlaying problem is, I need to encode a URL in a servlet ALWYAS with the session ID. But it seems that the "response.encodeURL()" Method only does this if Cookies are disabled (=>therefor using URL-Rewriting with the sessionID in the URL).
What would be an alternative to always encode a URL with a session ID in a servlet? As the first question implies I wanted to build the sessionid on my own but I therefore need the sessionID-Parameter Name that however seems not be be standardized, so I somehow need to get the Parameter-Name from somewhere...)
UPDATE:
The intention is to keep the SessionManagement Functionality provided by the Servlet-Container and not turn it off completely. I need to pass a Callback URL to a third party system that I want to always contain the SessionURL. So I only want to encode this single URL always with the sessionID to minimize any security issues...
Thank you very much
Jan
The jsessionid isn't actually a request parameter, it's encoded on to the URL itself, and then decoded and removed by the container before it gets as far as your controller. The value of jsessionid itself can be retrieved from HttpSession.getId().
If you want to stop Tomcat from using cookies, then you can provide a tomcat-specific context.xml file under WEB-INF, containing something like this:
<Context cookies="false" path="/path/to/my/webapp">
</Context>
This will disable all cookies for that webapp, and tomcat should then automatically encode all session IDs on to the URL instead.