Solved

How to store cookies for a combobox?

Posted on 2001-06-22
21
509 Views
Last Modified: 2008-02-20
Here's the code that I use to store cookies, but its not working?
This is on a JSP.  Its a combo-box and I want the cookie to stor the name  and value pair.  

Could someone please help?

<%
String s_show_name  = request.getParameter ( "show_name" );

Cookie[] cookie = request.getCookies();
for ( int i=0; i < cookie.length; ++i ) {
//   out.println ( cookie[ i ].getName () + " Test1--> " + cookie[ i ].getValue () );
     if ( cookie[ i ].getName ().equals ( "show_name" ) ) {
                s_show_name = cookie[ i ].getValue ();
     }
}s_select = getComboBox ( null, "ShowName", "show_name", s_shows, s_show_name );
out.println ( s_select );
%>

0
Comment
Question by:sdesar
  • 9
  • 9
  • 2
  • +1
21 Comments
 
LVL 12

Expert Comment

by:ahosang
ID: 6220543
The code you have doesn't set cookies only reads them. Where is the response.addCookie(cookie) function? Also what's your getComboBox function do?
0
 

Author Comment

by:sdesar
ID: 6221294
Where should I set the cookie on the JSP page ie., the addCookie?

The getComboBox funtion is a drop-down combo-box.
It allows the user to select their choice of Depatrment.
Once they select Ex. History, it displays all the queries for that department.
so its looks something like this
<select>  ... options  .. </select>
0
 
LVL 12

Expert Comment

by:ahosang
ID: 6221481
You would need to have the cookie details, then create a cookie and set it wherever you set your response headers in your code once that examines the user's http request:

<%
String s_show_name;
s_show_name  = request.getParameter("show_name");
if ((s_show_name!=null)&&(s_show_name!="")) {
  Cookie cookie=new Cookie("show_name", s_show_name);
  cookie.setMaxAge(60*60*24); // cookie last for a day
  response.addCookie(cookie);
}
Cookie[] cookie = request.getCookies();
for ( int i=0; i < cookie.length; ++i ) {
//   out.println ( cookie[ i ].getName () + " Test1--> " + cookie[ i ].getValue () );
    if ( cookie[ i ].getName ().equals ( "show_name" ) ) {
               s_show_name = cookie[ i ].getValue ();
    }
}
if ((s_show_name==null)||(s_show_name.equals("")) {
  s_show_name="defaultvalue";
}
s_select = getComboBox ( null, "ShowName", "show_name", s_shows, s_show_name );
out.println ( s_select );

%>

Obviously this is done after the user selects something and submits to your page again. Then you know which department to show. In the case of the user visiting for the first time you need to set a default value to show.
0
 

Author Comment

by:sdesar
ID: 6229425
I implemented your suggestion, but I am still just getting the default values.

When I added this after response.addCookie(cookie)
out.println (" add Cookie"  + cookie );

I got no results.

It seems as if the if statement was never triggered.

Any clues or suggestions?

Thanks!
0
 
LVL 12

Expert Comment

by:ahosang
ID: 6232556
See this line here:

if ((s_show_name!=null)&&(s_show_name!=""))
Change to :
if ((s_show_name!=null)&&(!s_show_name.equals("")))

You can see I've used the equals method in the other parts but this was just a javascript-ism (I do a lot more javascript). That should work.
0
 

Author Comment

by:sdesar
ID: 6233124
I modified it as you mentioned.. still the s_show_name is null,

I placed a couple of println stmts-
showName: null
Cookie[Ljavax.servlet.http.Cookie;@e0f7d97f
JSESSIONID Test1--> xjmxzoydf1
showName:null

Here's what the HTML looks like when I view source.

 <label> Show/Department:    <select name="show_name" value="ANY" onChange="checkShow(this);">
    <option selected>ANY</option>    <option>design</option>
</label>

PS. I understand that the first time its null but the next time the value should be set to what I selected  previously . example ., design, instead of ANY.

Any suggestions!
Thanks for helpine me!
0
 
LVL 12

Expert Comment

by:ahosang
ID: 6233225
OK, I'm missing some thing simple. Would it be possible to give me the whole jsp page so I can work through it. This is bugging me.
0
 

Author Comment

by:sdesar
ID: 6233488
I know its bugging me too!
Thanks for helping me.
Here's the JSP-


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<head>
<SCRIPT LANGUAGE="JavaScript">
<!-- Begin -->

function textCounter(field, countfield, maxlimit) {
if (field.value.length > maxlimit) {// if too long...trim it!
field.value = field.value.substring(0, maxlimit);
// otherwise, update 'characters left' counter
alert ('only 4000 chars allowed');
}else
countfield.value = maxlimit - field.value.length;
}
// End -->
</script>


<%@ include file="Utilities.jsp" %>
<title>Issue Submission Form</title>

<SCRIPT LANGUAGE="JavaScript">
function validate(form) {

mUv=form.summary.value;
       if (mUv=='' || mUv=="null")
       {
         alert('Summary is a required field. Please try again.');
           return false;
         }
mDv=form.description.value;
       if (mDv=='' || mDv=="null")
       {
         alert('Description is a required field. Please try again.');
           return false;
         }



mZv=form.show_name.selectedIndex;
  if (mZv == '0')
  {
        alert('Please select a Show or Department.' );
        return false;
  }


mTv=form.type_name.selectedIndex;
  if (mTv == '0')
  {
       alert('Please select a Type.');
       return false;
  }

mLv=form.location.value;
   if (mLv=='' || mLv=="null")
   {
      alert ('Location is a required field. Please try again.');
      return false;
   }

}

function checkPriority(combo) {
  mPv=combo.selectedIndex;
  if (mPv=='4')
  {
     return alert('This is a stopper.  Are you sure? ' );
  }
}

function checkShow(combo){
  mZv=combo.selectedIndex;
  if (mZv == '0')
  {
        return alert ('Please select a Show or Department' );
  }

}

</script>
</head>
<BODY marginheight="0" marginwidth="0" leftmargin="0" topmargin="0">

<br>
<TABLE BORDER=0 CELLSPACING=0 CELLPADDING=0 WIDTH="170" summary="Left Contextual Navigation Table" >
  <TR>
    <TD NOWRAP WIDTH="10"></TD>
    <TD NOWRAP WIDTH="10"></TD>
    <TD NOWRAP WIDTH="130"></TD>
    <TD NOWRAP WIDTH="10"></TD>
    <TD NOWRAP WIDTH="10"></TD>
  </TR>
  <TR>
    <TD VALIGN=TOP COLSPAN="2" WIDTH="20" BGCOLOR="#336699"><font size="3"><IMG SRC="/jsp//images/tl_navcorner_20.gif" ALT="" BORDER=0 height=20 width=20></font></TD>
    <TH ALIGN=CENTER NOWRAP WIDTH="130" BGCOLOR="#336699"> <font color="#FFFFFF" size="3" class="menu_header">submit
      issue</font> </TH>
    <TD VALIGN=TOP COLSPAN="2" WIDTH="20" BGCOLOR="#336699"><font size="3"><IMG SRC="/jsp/images/navcorner_20.gif" ALT="" BORDER=0 height=20 width=20></font></TD>
  </TR>
  <TR> </TR>
</TABLE>

<%@ include file="system.html" %>

<form name="mainForm" accept-charset="UNKNOWN" method="post"
        action="/servlet/forwardto" onSubmit="return validate(this);">
  <p>
    <input type="hidden" name="destination" value="gts_insert">


    <%
java.io.PrintWriter cnull = new PrintWriter ( new spijava.basic.CuNullStream () );

String s_shows = getShows ( cnull ); //request.getParameter ( "show_list" );
String s_show_name  = request.getParameter ( "show_name" );
String s_types   = getTypes ( cnull ); //request.getParameter ( "type_list" );
String s_type_name  = request.getParameter ( "type_name" );
String s_error_report = request.getParameter ( "error_report" );

if ( null != s_error_report ) {
    out.println ( "<h1>ERROR: " + s_error_report + "</h1> <br /><hr />" );
}

 out.println ( "showName: " + s_show_name);
//GetCookie Name and Value
if ((s_show_name!=null)&&(!s_show_name.equals(""))){
  Cookie cookie = new Cookie("show_name", s_show_name);
  cookie.setMaxAge(60*60*24);
  response.addCookie(cookie);
  out.println ( "Cookie" + cookie  + "\n");
}
Cookie[] cookie = request.getCookies();
out.println ( "Cookie" + cookie  + "\n");
for ( int i=0; i < cookie.length; ++i ) {
    out.println ( cookie[ i ].getName () + " Test1--> " + cookie[ i ].getValue () );
    if ( cookie[ i ].getName ().equals ( "show_name" ) ) {
         s_show_name = cookie[ i ].getValue ();
    }
    out.println ( "showName:" + s_show_name  + ": " + cookie[ i ].getValue ());

}

if ((s_show_name==null)||(s_show_name.equals(""))){
   s_show_name = "ANY";
}


String s_select = getComboBox (null, "<a href=\"/jsp/Faq_new.html#type\" target=\"detail\"> Type </a>", "type_name", "UNDEFINED," + s_types, s_type_name );
out.println ( s_select );
%>
    <b class="manditory_text"><font color="#FF0000">*</font></b>
    <%
s_select = getComboBox ("checkShow(this);", "Show/Department", "show_name", "ANY," + s_shows, s_show_name );
out.println ( s_select );
%>
    <br />
  <hr />
  <span class="default_text"><b class="manditory_text"><font color="#FF0000">*</font></b> Cube/Office#:</span>
  <input name="location" type="text" size="20" value='<%= removeNull(request.getParameter ("location")) %>' />
 


  <hr />
  <table border="0">
  <th colspan=4>  </th>
    <tr>
      <TD> <b class="manditory_text"><span class="manditory_text"><font color="#FF0000">*</font></span><span class="default_text">
        </span></b><span class="default_text"> User Name:</span> </td>
    </tr>
  </table>
  <hr />
  <p><b class="manditory_text"><span class="manditory_text"><font color="#FF0000">*</font></span><span class="default_text">
    </span></b><span class="default_text"> Summary</span> <br />
    <input name="summary" type="text" value='<%= removeNull(request.getParameter ( "summary" )) %>' size="80" />
    <br />
  </p>
  <hr />
  <p><b class="manditory_text"><span class="default_text"><font color="#FF0000">*</font>
    </span></b><span class="default_text"> Description </span>
    <font size="1" face="arial, helvetica, sans-serif"> ( You may enter up to 125 characters. ) </font>
<br />
    <textarea cols="80" name="description" rows="5" wrap="HARD"
    onKeyDown="textCounter(this.form.description,this.form.remLen,3500);"
    onKeyUp="textCounter(this.form.description,this.form.remLen,3500);" >
    <%= removeNull(request.getParameter ( "description" )) %></textarea>
    <br>
  </p>

  <hr />
  <table width="77%" border="0" cellspacing="2" cellpadding="0">
    <tr>
      <td width="34%" class="default_text">
        <div align="left">Notification List (comma separated e-mail list):</div>
      </td>
      <td width="66%">
        <input name="notify" type="text" value='<%= removeNull(request.getParameter ( "notify" )) %>' size="45" />
      </td>
    </tr>
  </table>
  <p class="default_text"><font color="#FF0000"><br>
    " * " Indicates Required Fields</font> </p>
  <p>
<input type="submit" value="Submit"  >
  </p>
</form>

</BODY>
</html>
0
 
LVL 12

Accepted Solution

by:
ahosang earned 50 total points
ID: 6233619
Got it:
Look at this simple page and examine the code. It's very late now for me, so I'm off to bed but notice the else code before the getCookies function and I hope you are using the forward method of RequestDispatcher rather than sendRedirect. Talk to you tomorrow.

JSP page:
<html>
<head>
     <title>Untitled</title>
</head>

<body>
<%
String s_show_name=request.getParameter("show_name");

if ((s_show_name!=null)&&(!s_show_name.equals(""))){
  Cookie cookie = new Cookie("show_name", s_show_name);
  cookie.setMaxAge(60*60*24);
  response.addCookie(cookie);
  out.println ( "Cookie" + cookie  + "<br>\n");
} else {
  Cookie[] cookie = request.getCookies();
  out.println ( "Cookie" + cookie  + "\n");
  for ( int i=0; i < cookie.length; ++i ) {
    out.println ( cookie[ i ].getName () + " Test1--> " + cookie[ i ].getValue()+"<br>");
    if ( cookie[ i ].getName ().equals ("show_name")) {
      s_show_name = cookie[ i ].getValue ();
    }
  }
}
out.println(s_show_name+"<br>");
if (s_show_name==null) {
  s_show_name="ANY";
}
%>
<form action="/servlet/simpleServlet">
<select name="show_name">
    <option value="ANY" <% if (s_show_name.equals("ANY")) {out.println("selected");} %>>ANY</option>
    <option value="design" <% if (s_show_name.equals("design")) {out.println("selected");} %>>design</option>
     <option value="hello" <% if (s_show_name.equals("hello")) {out.println("selected");} %>>hello</option>
</select>
<input type="submit">
</form>

</body>
</html>

simpleServlet:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class simpleServlet extends HttpServlet {
  public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException {
    resp.setContentType("text/html");
    PrintWriter out = resp.getWriter();
    String title = "Reading 3 request parameters";
    try {
       RequestDispatcher dispatcher=getServletContext().getRequestDispatcher("/showname.jsp");
       dispatcher.forward(req, resp);
     } catch (ServletException se) {}
       catch (IOException ioe) {}
  }
  public void doPost(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException {
    doGet(req, resp);
  }
}
0
 

Author Comment

by:sdesar
ID: 6274240
Thanks for the response.  The cookies are still not working.
It seems as though I always default to the else part of the code.
It never get to the setting cookies part of the code:-
if ((s_show_name!=null)&&(!s_show_name.equals(""))){
 Cookie cookie = new Cookie("show_name", s_show_name);
 cookie.setMaxAge(60*60*24);


Yes.. I am using the forward and not sendRedirect!

Any sussgestions?
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 12

Expert Comment

by:ahosang
ID: 6274401
Just a snippet of code:

if ((s_show_name!=null)&&(!s_show_name.equals(""))){
  Cookie cookie = new Cookie("show_name", s_show_name);
  cookie.setPath("/"); //NOTE THIS NEW LINE
  cookie.setMaxAge(60*60*24);
  response.addCookie(cookie);
  out.println ( "Cookie" + cookie.getName()  + "<br>\nCookie set!<br/>\nCookie value= "+cookie.getValue()+"<br />\n");
} else {....

}

We have to set the path to include all directories because the path will be changed to the servlet path when the cookie is set(the servlet URL is the URL when using forward) so when the page is requested anew(after browser has been closed or page refreshed) the cookie is not being sent to the server because the jsp path was not under the servlet directory. The cookie actually was being set though.

As simple as that!! Phew!
0
 

Author Comment

by:sdesar
ID: 6274506
Its still not working.  
The else part is still being triggred.
BUT Not the name value pairs.
0
 

Author Comment

by:sdesar
ID: 6274509
PS.. I added this line.
cookie.setPath("/"); //NOTE THIS NEW LINE

Even after this its NOT working!
0
 

Author Comment

by:sdesar
ID: 6274561
OOps its was the path!
its working!

Thanks a million!
0
 
LVL 12

Expert Comment

by:ahosang
ID: 6274572
glad to help :-)
0
 

Author Comment

by:sdesar
ID: 6274897
I am using frames and when I placed this code in the original application ie JSP ..the cookies are not working, it defaults to ANY?

Would you have any suggestions to fix this weired behavior?
0
 
LVL 12

Expert Comment

by:ahosang
ID: 6274998
Could you explain a bit more?
0
 
LVL 1

Expert Comment

by:Moondancer
ID: 6331984
It's time to clean up this topic area and that means taking care of this question. Your options at this point are:

1. Award points to the Expert who provided an answer, or who helped you most. Do this by clicking on the "Accept Comment as Answer" button that lies above and to the right of the appropriate expert's name.

2. PAQ the question because the information might be useful to others, but was not useful to you. To use this option, you must state why the question is no longer useful to you, and the experts need to let me know if they feel that you're being unfair.

3.  Ask Community Support to help split points between participating experts.  Just comment here with details.

4.  Delete the question because it is of no value to you or to anyone else.  To use this option, you must state why the question is no longer useful to you, and the experts need to let me know if they feel that you're being unfair.

If you elect for option 2, 3 or 4, just post comment with details here and I'll take it from there.  We also request that you review any other open questions you might have and update/close them.  Display all your question history from your Member Profile to view details.

PLEASE DO NOT AWARD THE POINTS TO ME.

____________________________________________



Hi Experts:

In the event that the Asker does not respond, I would very much appreciate your opinions as to which Expert ought to receive points (if any) as a result of this question.  Likewise, you can also suggest that I PAQ or delete the question.

Experts, please do not add further "answer" information to this question.  I will be back in about one week to finalize this question.

Thank you everyone.

Moondancer :)
Community Support Moderator @ Experts Exchange

P.S.  Engineering has been advised about the error in the comment date/time sort order.  REGARDING POINTS and more:  http://www.experts-exchange.com/jsp/cmtyHelpDesk.jsp  
When using points to ask a question, you assign the point value of the question based on its difficulty. As a guide, a basic question is worth 50 question points, an intermediate question is worth 100 points, and an advanced question is worth about 200 points. The more question points assigned to a question, the more likely it is that it will be answered.

When you accept an Expert's solution as an answer, the question points you offered are deducted from your account. The Expert's score is increased by the sum of the number of points you offered for the question, multiplied by the grade you assigned to the answer. The Expert is then awarded Expert Points based on this score.

0
 

Expert Comment

by:teacher_mod
ID: 6374581
This question has been abandoned. Would the experts please indicate how
this should be closed out. Is there a comment which should be accepted?
Should the points be split? Should it be reduced to zero points and PAQed?
should it be deleted?  In the absence of direction, the default will be
for me to delete.

TIA for helping to clean up the old questions.

teacher_mod
Community Support Moderator
Experts-Exchange
teacher_mod@experts-exchange.com


0
 
LVL 12

Expert Comment

by:ahosang
ID: 6374597
I'd have to say my comments of course being the only commenter and judging by this response:
>>>OOps its was the path!
>>>its working!

>>>Thanks a million!
The code worked.
0
 

Expert Comment

by:teacher_mod
ID: 6374621
LOL  I was move through post the standard boiler plate, and missed that this one was good to go.  Points awarded.

teacher_mod
Community Support Moderator
Experts-Exchange
teacher_mod@experts-exchange.com

0

Featured Post

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
HTML table 7 54
2 CSS questions 11 33
jquery contains method to look for a paragraph tag 2 23
Setting Up a Responsive Form 24 41
Popularity Can Be Measured Sometimes we deal with questions of popularity, and we need a way to collect opinions from our clients.  This article shows a simple teaching example of how we might elect a favorite color by letting our clients vote for …
SASS allows you to treat your CSS code in a more OOP way. Let's have a look on how you can structure your code in order for it to be easily maintained and reused.
In this Micro Tutorial viewers will learn how to create navigation buttons that change on rollover, using CSS (Continuation of the CSS Image Sprite tutorial) Create a parent ID for all the list items       - Specify position: absolute and display: block…
In this tutorial viewers will learn how to embed Flash content in a webpage using HTML5. Ensure your DOCTYPE declaration is set to HTML5: "<!DOCTYPE html>": Use the <object> tag to embed Flash content.: To specify that the object is Flash content, d…

707 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

15 Experts available now in Live!

Get 1:1 Help Now