Solved

Not setting cookie

Posted on 2000-05-15
15
383 Views
Last Modified: 2010-04-01
Hi!
First of all I am very much new to Java itself.
I have one login form which has 2 fields for username and password.
Now first of all how do you set cookie on clients m/c.
I have to also pass username and password entered by user to that cookie for storing.
Please do give me some sample code(small one if possible)
I have seen some code for setting cookie but passing username and password from .jhtml page(jhtml since using ATG Dynamo) to cookie.
here is my small code also which I have written
response.setContentType("text/html");
PrintWriter outpage = response.getWriter();

javax.servlet.http.HttpSession  hs = request.getSession(true);
String sessid= new String(hs.getId());
outpage.println("SessionId= "+sessid);


Cookie cookie = new Cookie("username","arpit");
response.addCookie(cookie);


Cookie[] cookies = request.getCookies();
for(int i=0;i<cookies.length;i++)
{
outpage.println("getpath = "+cookies[i].getPath());
outpage.println("getname= "+cookies[i].getName());
outpage.println("getvalue = "+cookies[i].getValue());
}

Here it is not setting the cookie also.
i.e. I cannot find any text file with word "username" etc.......

what does this getvalue and putvalue do and what is the parameters it accept.
Say if I pass the username from my form in a variable named "abc" then how can I use putvalue?
I would like to know that say once if u have set the cookie how do you retrieve it means first of all how do I set a cookie with some name say "xyz" and then retrieve it, if it is set.
I am bit confused about this.
Please tell me methods to use for:
1)to set a cookie alongwith passing username and password from form,if cookie is not set.
2)if it is set how to retrieve it and get the username and password from it.
Please make it fast.
I just need the method names to be used for particular functionality.
One more problem is ,that I can't find the text file in which the cookie is set
what about that?

 
Thanks.

0
Comment
Question by:highmarks
  • 6
  • 3
  • 2
  • +3
15 Comments
 
LVL 3

Expert Comment

by:rjackman
Comment Utility
hey arpit
try this link i think it will help u
http://www.davidreilly.com/java/java_network_programming/#6.7
RJackman
0
 
LVL 3

Accepted Solution

by:
rjackman earned 100 total points
Comment Utility
hey arpit
try this link i think it will help u
http://www.davidreilly.com/java/java_network_programming/#6.7
RJackman
0
 
LVL 3

Expert Comment

by:rjackman
Comment Utility
oops..! sorry for posting twise
0
 
LVL 7

Expert Comment

by:Ravindra76
Comment Utility

Why U need Cookies when U are using Sessions ??

Use Session only

From jsdk src

Interface javax.servlet.http.HttpSession

public interface HttpSession

The HttpSession interface is implemented by services to provide an association between an HTTP client and HTTP server.
This association, or session, persists over multiple connections and/or requests during a given time period. Sessions are used to
maintain state and user identity across multiple page requests.

A session can be maintained either by using cookies or by URL rewriting. To expose whether the client supports cookies,
HttpSession defines an isCookieSupportDetermined method and an isUsingCookies method.

HttpSession defines methods which store these types of data:

     Standard session properties, such as an identifier for the session, and the context for the session.
     Application layer data, accessed using this interface and stored using a dictionary-like interface.

The following code snippet illustrates getting and setting the the session data value.

 //Get the session object - "request" represents the HTTP servlet request
 HttpSession session = request.getSession(true);
 

 //Get the session data value - an Integer object is read from
 //the session, incremented, then written back to the session.
 //sessiontest.counter identifies values in the session
 Integer ival = (Integer) session.getValue("sessiontest.counter");
 if (ival==null)
     ival = new Integer(1);
 else
     ival = new Integer(ival.intValue() + 1);
 session.putValue("sessiontest.counter", ival);
 

When an application layer stores or removes data from the session, the session layer checks whether the object implements
HttpSessionBindingListener. If it does, then the object is notified that it has been bound or unbound from the session.

An implementation of HttpSession represents the server's view of the session. The server considers a session to be new until it
has been joined by the client. Until the client joins the session, the isNew method returns true. A value of true can indicate one
of these three cases:

     the client does not yet know about the session
     the session has not yet begun
     the client chooses not to join the session. This case will occur if the client supports only cookies and chooses to reject
     any cookies sent by the server. If the server supports URL rewriting, this case will not commonly occur.

It is the responsibility of developers to design their applications to account for situations where a client has not joined a session.
For example, in the following code snippet isNew is called to determine whether a session is new. If it is, the server will require
the client to start a session by directing the client to a welcome page welcomeURL where a user might be required to enter
some information and send it to the server before gaining access to subsequent pages.

 //Get the session object - "request" represents the HTTP servlet request
 HttpSession session = request.getSession(true);
 

 //insist that the client starts a session
 //before access to data is allowed
 //"response" represents the HTTP servlet response
 if (session.isNew()) {
     response.sendRedirect (welcomeURL);
 }
 



In the above example ,

he stored primitive data type in the line

 session.putValue("sessiontest.counter", ival);

U can store Objects also

If U want multiple values in session, construct a object with different fields put
that object.

DOn't use cookies when u are using Sessions

:)
0
 
LVL 2

Author Comment

by:highmarks
Comment Utility
hi!
Actually I am new to all this so what you suggest will be fine, but it will be kind of you if you can tell me that can I save username and password of my client on client's machine, so that when he again visits my site he does not have to login.
If that is possible then how?
Thankyou.
0
 
LVL 2

Author Comment

by:highmarks
Comment Utility
As far as my knowledge is concerned I know that for storing username and password on client's m/c you need some text file to store that which is called cookie,right?
0
 
LVL 1

Expert Comment

by:yanchou
Comment Utility
ravindra76

There are some points where Cookie is useful.

1. Cookie is easier for client to maintain the session(magic number). Otherwise, client side have to explictly manipulat this magic number.

2. In case client is a java application instead of HTML page (in this case, browser will handle the cookie). Cookie will help you write some geneic communication API so the GUI programmer don't need to worry anything about Session.



highmarks:

You should use session for sure, But you should not use Cookie to keep UserID and password



I did write this communication API 1 and half year ago and it work. Let me check if I still have the code for you.

BTW, Cookie is not the only way to keep the session.

Thanks
0
Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

 
LVL 7

Expert Comment

by:Ravindra76
Comment Utility

Hi yanchou ,

  Clients can disable cookies in browsers. so Sessions are USeful.

Session will also use cookies internally for sessiioID. But when cleint disable cookies, Webserver will automatically shift to URL rewriting.

SO basing on Cookies is useless sicne so may people disable cookies.

:)
 
0
 
LVL 2

Author Comment

by:highmarks
Comment Utility
ravindra76 and yanchou
Since our existing site is like that only and we do not deal with any such critical or confidential data, it is required to store cookie alongwith username and password in the cookie.
But i am unable to set the cookie and if browser has cookie disabled I need not worry.
PLEASE TELL ME HOW TO SET A COOKIE WHICH WILL BE VALID FOR ONE YEAR AND SHOULD ALSO CONTAIN USERNAME AND PASSWORD.
And please this username and password is not at all critical so it's ok if someone uses that username and password.
THANKYOU.
Please be fast please...........

0
 
LVL 5

Expert Comment

by:mbormann
Comment Utility
Arpit,

here are some URL's ,I do hope that they help you out, I will take the laptop home this week and if you do have problems mail me. Feel free to ask buddy.

In detail
http://java.sun.com/docs/books/tutorial/servlets/client-state/cookies.html

In short
http://www.javacoffeebreak.com/faq/faq0057.html
http://www.javacoffeebreak.com/faq/faq0058.html
http://www.javacoffeebreak.com/faq/faq0059.html

Some nice explanation
http://www.weblogic.com/docs/classdocs/API_servlet.html#cookies

>>>HOW TO SET A COOKIE WHICH WILL BE VALID FOR ONE YEAR AND SHOULD ALSO CONTAIN USERNAME AND PASSWORD

//user
Cookie m1 = new Cookie("user", "arpit");
m1.setMaxAge(Integer.MAX_VALUE);//calculate the year in seconds and set it here

res.addCookie(m1);

//paswrod
Cookie m2 = new Cookie("password", "arpit");
m2.setMaxAge(Integer.MAX_VALUE);//calculate the year in seconds and set it here

res.addCookie(m2);

With Warmest Regards
Amit
0
 
LVL 2

Author Comment

by:highmarks
Comment Utility
Hi Amit,
I think when you tell res.addcookie()
It will make a text file in which cookie will be stored right?
If that is the case it is not making any text file.
Can u throw some light on it?
Thanks.
0
 

Expert Comment

by:diegojimenez
Comment Utility
hello highmarks.
You can use cookies, but clients can disable cookies in browsers.
If you would like use cookies you can make this with JavaScript; is more easy;.
This is the code with JavaScript:

// Sets cookie values. Expiration date is optional//function setCookie(name, value, expire) {          document.cookie = name + "=" + escape(value)          + ((expire == null) ? "" : ("; expires=" + expire.toGMTString()))}


Notice the use of escape to encode special characters (semicolons, commas, spaces) in the value string. This function assumes that cookie names do not have any special characters.
The following function returns a cookie value, given the name of the cookie:


function getCookie(Name) {          var search = Name + "="          if (document.cookie.length > 0) { // if there are any cookies                    offset = document.cookie.indexOf(search)                     if (offset != -1) { // if cookie exists                               offset += search.length                               // set index of beginning of value                              end = document.cookie.indexOf(";", offset)                               // set index of end of cookie value                              if (end == -1)                                         end = document.cookie.length                              return unescape(document.cookie.substring(offset, end))                    }           }}
Notice the use of unescape to decode special characters in the cookie value.
0
 
LVL 5

Expert Comment

by:mbormann
Comment Utility
>>>It will make a text file in which cookie will be stored right?

I think so but I am not sure ,have never had occasion to use Cookies.r u using a browser on client side or Java application?
0
 
LVL 2

Author Comment

by:highmarks
Comment Utility
Comment accepted as answer
0
 
LVL 2

Author Comment

by:highmarks
Comment Utility
good link rjackman
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

For customizing the look of your lightweight component and making it look opaque like it was made of plastic.  This tip assumes your component to be of rectangular shape and completely opaque.   (CODE)
By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now