I set my cookie in my controller, return a new modelandview, the cookie gets set. However, on any other request, the cookie is lost.
Also, when I reset the cookie to some other value, the value doesn't change when the page is loaded. It does change after page refresh and it again gets lost on any other request.
During all these multiple requests, JSESSIONID remains the same.
In controller:
Cookie locationCookie = new Cookie("locCookie", loc);
locationCookie.setMaxAge(60*60*24*365); //one year
response.addCookie(locationCookie);
return FWD_HOME;
In JSP (FWD_HOME):
<jsp:include page="/WEB-INF/jsp/fragments/header.jsp"></jsp:include>
<jsp:forward page="/HOME"></jsp:forward>
In JSP (header):
<%
Cookie cookie = null;
Cookie[] cookies = null;
cookies = request.getCookies();
String locValue = null;
if( cookies != null ){
for (int i = 0; i < cookies.length; i++){
cookie = cookies[i];
out.print(cookie.getName()+"=");
out.print(cookie.getValue()+";");
if("locCookie".equals(cookie.getName())){
locValue = cookie.getValue();
}
}
}
out.print(locValue);
%>
What am I doing wrong here?
I got the solution. along with Cookies on localhost with explicit domain, setting the path to "/" made it work.
Related
Lets say..
if i hit google with https://www.google.com it will create a session, for the responce it
will create url with session tokn like..
https://www.google.co.in/?gfe_rd=cr&ei=oFBjVJSvLqnM8gft5YDwAQ&gws_rd=ssl.
My question is
am connecting to google with the code:
URL url = new URL(test);
URLConnection conn = url.openConnection();
this will connect to google.
for this google creates a session.
then how would i get a session token back to my code?
You can get the session token from the cookie of the browser. You can, find the cookie settings->advanced settings->privacy->content settings->allcookie and site data then search www.google.com and select sid and copy the content .
You can extract any cookie, not only the one containing the session with the following approach:
Since a server may set multiple cookies in a single request, we will need to loop through the response headers, looking for all headers named "Set-Cookie".
String headerName=null;
for (int i=1; (headerName = uc.getHeaderFieldKey(i))!=null; i++) {
if (headerName.equals("Set-Cookie")) {
String cookie = urlConn.getHeaderField(i);
The string returned by the getHeaderField(int index) method is a series of name=value separated by semi-colons (;). The first name/value pairing is actual data string we are interested in (i.e. "sessionId=0949eeee22222rtg"), the subsequent name/value pairings are meta-information that we would use to manage the storage of the cookie (when it expires, etc.).
cookie = cookie.substring(0, cookie.indexOf(";"));
String cookieName = cookie.substring(0, cookie.indexOf("="));
String cookieValue = cookie.substring(cookie.indexOf("=") + 1, cookie.length());
This is basically it. We now have the cookie name (cookieName) and the cookie value (cookieValue).
the above explanation was based on example provided in http://www.hccp.org/java-net-cookie-how-to.html#retrieving_cookies
A more sophisticated approach is to use CookieAccessor class:
public void getCookieUsingCookieHandler() {
try {
// Instantiate CookieManager;
// make sure to set CookiePolicy
CookieManager manager = new CookieManager();
manager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(manager);
// get content from URLConnection;
// cookies are set by web site
URL url = new URL("http://host.example.com");
URLConnection connection = url.openConnection();
connection.getContent();
// get cookies from underlying
// CookieStore
CookieStore cookieJar = manager.getCookieStore();
List <HttpCookie> cookies =
cookieJar.getCookies();
for (HttpCookie cookie: cookies) {
System.out.println("CookieHandler retrieved cookie: " + cookie);
}
} catch(Exception e) {
System.out.println("Unable to get cookie using CookieHandler");
e.printStackTrace();
}
}
In any approach you follow you need to know what is the name of the cookie holding the session id, so that you can get the value from it. E.g a java web application usually creates a cookie with name "JSESSIOINID"
I have a situation where i need to set cookie in JSP and i need to get those cookie in normal java class.
The JSP:
CookieManager manager = new CookieManager();
CookieHandler.setDefault(manager);
CookieStore cookieJar = manager.getCookieStore();
// create cookie
HttpCookie cookie = new HttpCookie("UserName", "John Doe");
// add cookie to CookieStore for a
// particular URL
URL url = new URL("http://localhost:8080");
url.openConnection().connect();
cookieJar.add(url.toURI(), cookie);
System.out.println("Added cookie using cookie handler");
%>
Below is the Java class [not a servlet class] and this class is running in the server and this is invoked not after the JSP call but somewhere in the application only if any event occurs. below is the code where i wrote to capture cookies.
URL url = new URL("http://localhost:8080");
URLConnection conn = url.openConnection();
conn.getContent();
CookieManager cm = new CookieManager();
CookieHandler.setDefault(cm);
cm.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
CookieStore cs = cm.getCookieStore();
List <HttpCookie> cookies = cs.getCookies();
for (HttpCookie cookie: cookies) {
System.out.println("CookieHandler retrieved cookie: " + cookie);
}
would this scenario works if i want to retrieve the cookies in non servlet class?
The output of the above code will return empty list.
However if i write a servet class with request.getCookie("UserName") I will see the cookie value.
Here i need to understand how would i get the cookie value without using request object.
Because request object is not always passed in multiple invocation of java class. And i am not using session.
please let me know if you have any better approach.
Thanks-
Instead Use the getHeaderFields() method from the connection Object to get the full list of Name-Value pairs representing the header fields of the specific connection
Cookie information(if present)should be under the “Set-Cookie” header field.
Map<String, List<String>> headerFields = conn.getHeaderFields();
Set<String> headerFieldsSet = headerFields.keySet();
Iterator<String> hearerFieldsIter = headerFieldsSet.iterator();
Then iterate over the Set and check if the cookie is present. If it is present print it out.
while (hearerFieldsIter.hasNext()) {
String headerFieldKey = hearerFieldsIter.next();
if ("Set-Cookie".equalsIgnoreCase(headerFieldKey)) {
List<String> headerFieldValue = headerFields.get(headerFieldKey);
for (String headerValue : headerFieldValue) {
System.out.println("Cookie Found...");
String[] fields = headerValue.split(";\s*");
String cookieValue = fields[0];
System.out.println("cookieValue:" + cookieValue);
}
}
}
Y0u can refer this examle
This question already has answers here:
How do I keep a user logged into my site for months?
(2 answers)
Closed 5 years ago.
I have a login screen and i am authenticating users by checking credentials from database. But how can i implement Remember me check box? Like in gmail remember me(stay signed in) is present. I am using sign.jsp and Auth servlet (doPost) and oracle 10g ee for authentication.
You can use cookies for this purpose.
In your servlet response handler (doPost, doGet etc.) create a cookie in the following way -
if(remember_me_is_checked)
{
Cookie c = new Cookie("userid", userId.toString());
c.setMaxAge(24*60*60);
response.addCookie(c); // response is an instance of type HttpServletReponse
}
To read them, you can use something like this -
Cookie[] cookies = request.getCookies(); // request is an instance of type
//HttpServletRequest
boolean foundCookie = false;
for(int i = 0; i < cookies.length; i++)
{
Cookie c = cookies[i];
if (c.getName().equals("userid"))
{
string userId= c.getValue();
foundCookie = true;
}
}
Here is the official documentation for the Cookie class.
You can use cookies to help with your implementation. Something like this .
String userIdendificationKey="UserName";
Cookie cookie = new Cookie ("userIdendificationKey",userIdendificationKey);
// Set the age of the cokkie
cookie.setMaxAge(365 * 24 * 60 * 60);
//Then add the cookies to the response
response.addCookie(cookie);
and then check against the particular value later .
I don't know whether it is secure or not,but this is what i did.
In login.jsp head tag
<script type="text/javascript">
var isLoggedIn = "${isLoggedIn}";
if(isLoggedIn === true)
window.location.href="Home.jsp";
</script>
in body tag i added a check box for Remember Me as below
<input type="checkbox" id="RememberMe" name="rememberMe">
<label for="RememberMe">Remember Me</label>
In servlet doPost method i added the code below
if(userdetails are verified)
{
if(request.getParameter("rememberMe")!=null){
request.getSession().setAttribute("isLoggedIn", true);
}
RequestDispatcher rs = request.getRequestDispatcher("Home.jsp");
rs.forward(request, response);
}
else
{
RequestDispatcher rs = request.getRequestDispatcher("fail.jsp");
rs.include(request, response);
}
using this it will ask for the credentials at first time login,and it will store the login info in session parameters,if you try to access the site second time it will automatically goes to "Home.jsp" instead of "login.jsp"
please comment whether this method is good practice,any other modifications can be done.
Suggestions are welcome.
Take a look at Spring SecurityIt
It is a powerful and highly customizable authentication and access-control framework.
You can also check the code from Rose India, this will be more helpful to you.
I want to create a login page thats when the user select either remember username or remember me check box, a cookie should be generated, when the remember username checkbox is selected, it should store the username, when the remember me checkbox is selected it should store both the username and password to avoid retyping whena user returns to the login page.
I wrote the preceeding code to incorporate the functionality but on testing the page the user has to retype the username each time the login page is loaded. I am not able to identify the cause of the problem, can someone help me with this?
<%
String userName = request.getParameter("username");
String password = request.getParameter("password");
String rm_me = request.getParameter("rm_me");
String rm_uname = request.getParameter("rm_uname");
if (userName != null && password != null) {
if (rm_me != null) {
Cookie ckU = new Cookie("username", userName);
Cookie ckP = new Cookie("password", password);
response.addCookie(ckP);
} else {
if (rm_uname != null) {
Cookie ckU = new Cookie("username", userName);
}
}
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
if (cookies[i].getName().equals("username")) {
userName = cookies[i].getValue();
}
if (cookies[i].getName().equals("password")) {
password = cookies[i].getValue();
}
}
}
%>
You shouldn't be doing this kind of stuff in a JSP. You should use do it in a "controller" servlet and then forward the outcome to a JSP to (just) format the HTML response.
And I think your problem is most likely to be related to that. Specifically, I suspect that the response will already have been committed by the time that the scriptlet code executes. This means that your response.addCookie(...); call will be too late to add a SetCookie header to the response.
You should be able to confirm this by dumping the response headers when they leave the server or when they reach your browser ... or (less directly) by looking in the browser cookie store.
Pretty much any introductory book or tutorial on JSP would include examples of everything you want.
Any reasonably recent one will also tell you that using Java code in a JSP is very bad indeed, just don't do it.
Use JSTL instead.
I have a cookie, myCookie, that contains a hash value. This cookie is set to expire in one year and has a path of '/'. I need to update this cookie with a new hash value. When my JSP script is loaded I retrieve the cookie like so:
Cookie[] cookies = request.getCookies();
Cookie myCookie = null;
for (int i = 0; i < cookies.length; i += 1) {
if (cookies[i].getName().equals("myCookie")) {
myCookie = cookies[i];
break;
}
}
After determining that the value of the cookie needs to be updated, I do the following to update it:
myCookie.setValue("my new value");
response.addCookie(myCookie);
Examining the results, I now have two instances of myCookie: the original version with the correct expiration date and path, and the old, invalid, value; and a new cookie named "myCookie" that expires at the end of the session, with the correct value, and a path of the JSP document.
If I do:
myCookie.setValue("my new value");
myCookie.setPath(myCookie.getPath());
myCookie.setMaxAge(myCookie.getMaxAge());
response.addCookies(myCookie);
The same thing happens. I get two cookies with the same name and different properties.
Does a Cookie object not retain the properties from when it was retrieved? How can I update this cookie?
Note: I do not want to modify the path or the expiration date. I only want to update the value of the already set cookie.
Per section 3.3.4 of RFC 2965, the user agent does not include the expiration information in the cookie header that is sent to the server. Therefore, there is no way to update an existing cookie's value while retaining the expiration date that was initially set based solely on the information associated with the cookie.
So the answer to this question is: you can't do that.
Just set the path, ex:
cookie.setPath("/");
This should overwrite the old cookie value.
If you are manipulating cookies from within a JSP, one thing you will need to watch out for is whether or not the response has already been committed. Once content is written to the output stream, adding a cookie to the response is futile.
ServletResponseWrapper.isCommitted()
You can delete the old cookie, if the new one does not contain the same name, path, and domain by setting MaxAge to (0) http://download.oracle.com/javaee/1.3/api/javax/servlet/http/Cookie.html#setMaxAge(int)
def member = SecUser.get(userService.currentUser().id)
def cookies = request.getCookies()
def cookie;
def sum = 0;
def cookieSum = 0;
def cookieItems;
for(def i=0; i<cookies.size(); i++){
if (cookies[i].name == 'c17'){
cookie = cookies[i]
cookieItems = cookie.value.split('-')
println "cookieItems......."+cookieItems
if(params.itemId != null){
for(def j=0; j<cookieItems.size(); j++){
def oldItem = cookieItems[j].split('\\|')[0]
if(params.itemId != oldItem){
sum = sum + 1
}
}//Below code for Update your cookie value
if(sum == cookieItems.size()){
cookie.value = cookie.value +"-"+params.itemId+"|"+member.id
def b = cookie.value
cookie.setValue(b);
response.addCookie(cookie);
}
}
break
}
else{
cookieSum = cookieSum + 1
}
}
if ((cookieSum) == cookies.size()){
// Here ADD new cookie........
def a = params.itemId+"|"+member.id
cookie = new Cookie('c17',a.toString())
cookie.path = '/'
response.addCookie(cookie)
}
The Above code can help you for ADD a cookie and UPDATE the cookie value