Search code examples
javajspservletshttp-request-parameters

Preserving the selected value in an HTML select element after refreshing a JSP page


I have a JSP with drop down box. I select one option and submit that one. So now I get the information stored in the database of that selected option. Now I refresh the JSP (HTML page) automatically by setting in servlet as

//servlet code inside doGet() method
HttpSession session=request.getSession();
String selUrl=request.getParameter("urlsel");    
String opt=session.setAttribute("selectedUrl",selUrl);
String selopt=session.getAttribute("selectedUrl");
response.setHeader("Refresh","10;url="/SiteAvailabilityServlet?ursel="+selectedUrl);
//and forwarding request to result.jsp using RequestDispatcher..

//input.jsp code

<select name="urlsel">
<option value="abc">abc</option>
<option value="def">def</option>
</select>

For the first time when I select the option say abc and submitted manually it is giving me the correct result and showing the details from data base. After 10 seconds it is refreshed automatically with the same option abc (I do not want to change the option), but not displaying values. It is taking the

  request.getParameter("urlsel")    as null  after refreshing automatically.

Please help me. In result.jsp I am using

 <form method="get" action="/SiteAvaialabilityServlet">

Solution

  • I think your code should function if you replace this line :

    response.setHeader("Refresh","10;url="/SiteAvailabilityServlet?ursel="+selectedUrl);
    

    With this :

    response.setHeader("Refresh","10;url=/SiteAvailabilityServlet?urlsel="+ selopt);
    

    What changed is this :

    • An " was taken away from the URL in the header, I don't see why it should be there ;
    • It's urlsel not ursel ;
    • Why selectedUrl ? It's the name of the session attribute, what you want is the value of the session attribute. Since your have that (selopt), you might just want to use it.

    Your HTML may want to be better taken care of, as far as this line is concerned, an " is missing :

    <form method="get" action="/SiteAvaialabilityServlet> 
    

    So replace it with this :

    <form method="get" action="/SiteAvaialabilityServlet">
    

    Hope all those typos are not in your original code.

    P.S : Please do correct the code in your question to help everybody help you :).

    Best of luck.