[Last Call] Learn about multicloud storage options and how to improve your company's cloud strategy. Register Now

x
?
Solved

Not setting cookie

Posted on 2000-05-15
15
Medium Priority
?
408 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 3
  • 2
  • +3
15 Comments
 
LVL 3

Expert Comment

by:rjackman
ID: 2810304
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 400 total points
ID: 2810365
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
ID: 2810384
oops..! sorry for posting twise
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
LVL 7

Expert Comment

by:Ravindra76
ID: 2810681

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
ID: 2811794
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
ID: 2811810
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
ID: 2812456
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
 
LVL 7

Expert Comment

by:Ravindra76
ID: 2813182

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
ID: 2813361
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
ID: 2814766
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
ID: 2815864
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
ID: 2816849
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
ID: 2817352
>>>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
ID: 2849657
Comment accepted as answer
0
 
LVL 2

Author Comment

by:highmarks
ID: 2849658
good link rjackman
0

Featured Post

Tech or Treat!

Submit an article about your scariest tech experience—and the solution—and you’ll be automatically entered to win one of 4 fantastic tech gadgets.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
This video teaches viewers about errors in exception handling.
How to fix incompatible JVM issue while installing Eclipse While installing Eclipse in windows, got one error like above and unable to proceed with the installation. This video describes how to successfully install Eclipse. How to solve incompa…
Suggested Courses

650 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