Results 1 to 19 of 19
  1. #1
    sashi799 is offline Member
    Join Date
    Jul 2010
    Posts
    15
    Rep Power
    0

    Default Retaining value of checkbox when returning back from a servlet

    hello,

    I'm trying to retain the value of the checkbox when returning to the same servlet from another servlet. How can i implement it.

    Scenario:

    Servlet A has checkbox which post to servlet B then i want to go back to servlet A again and modify the checkbox that i selected before.


    So how do i maintain the previously selected checkboxes [i want the checkbox to be checked when it reloads] ???

    P.S. Hope my explanation is understandable.

  2. #2
    ajaysingh87 is offline Member
    Join Date
    Jul 2010
    Location
    India, Mumbai
    Posts
    5
    Rep Power
    0

    Default

    while submitting this page u store ur check box value in attribute , that attribute u need to store in session and when u return back to page B , u retrive that value from session and set through javascript as selected..(SINGH IS KING):)

  3. #3
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,014
    Rep Power
    20

    Default

    Not entirely clear.

    If Servlet A is doing the POST to Servlet B then it's not a checkbox, and it's simply a parameter. "checkbox" only has meaning on the browser. By the time you get to the servlet it is simply another parameter.

    Step us through the flow, from the browser submitting the form containing the checkbox.
    That is, Submit -> Servlet A -> forward or redirect to Servlet B -> etc etc.

  4. #4
    sashi799 is offline Member
    Join Date
    Jul 2010
    Posts
    15
    Rep Power
    0

    Default

    i got the idea of Httpsession but now my prob is the display part.

    Here is some section of my code:

    servelt A

    Java Code:
    ......
    out.println ("<input type=\"checkbox\" name=\"item\" value=\"Item 1\" > Item 1 <br>");
    out.println ("<input type=\"checkbox\" name=\"item\" value=\"Item 2\" > Item 2 <br>");
    out.println ("<input type=\"checkbox\" name=\"item\" value=\"Item 3\" > Item 3 <br>");
    ......
    servlet B

    Java Code:
    .....
    HttpSession session = req.getSession(true);
    String[] item;
    ...
    ...
    item = req.getParameterValues("item");
    req.getSession().setAttribute("item", item);
    ....
    ...
    out.println("&nbsp&nbsp<input type=\"submit\" name=\"back\" value=\"Back\">");
    ...
    ...
    if ((req.getParameter("back"))!= null)
    {
    	res.sendRedirect("/demo/servletA");
    }
    ...

    So when the submit button Back is press, How to retrive the session value in Servlet A and retain the checked value [display those checked boxes as checked]??

  5. #5
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,014
    Rep Power
    20

    Default

    Can I suggest you remove the html from the servlets?
    Forward to an html page or a JSP rather than have the servlet output the html...that's not the servlets job, and it'll make the flow a lot clearer.

    Right, whether you've done that or not you need to get the value of "checkbox" from the session and use that to decide whether the checkbox (html) attribute "checked" needs adding. But I would really split it out to a JSP first.

  6. #6
    sashi799 is offline Member
    Join Date
    Jul 2010
    Posts
    15
    Rep Power
    0

    Default

    @Tolls

    Yes you are right but the thing is i'm really new to java and stil yet to learn JSP [may be by this weekend :) ]

    My problem still persist ....any ideas????

  7. #7
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,014
    Rep Power
    20

    Default

    OK, that's what I suspected.
    And you are doing it the right way round...learning Servlets, so I can't be too harsh...:)
    Too many start with JSPs, which is a mistake in my opinion.

    Anyway, to take one of your checkboxes as an example:
    Java Code:
    out.println ("<input type=\"checkbox\" name=\"item\" value=\"Item 1\" > Item 1 <br>");
    is your current code.

    Now, what you want is to check if there is a "checkbox" attribute in the session. Presumably you have them numbered (ie "checkbox1" etc)? If that exists then you want to add "checked" in the output string.

    So:
    Java Code:
    String checkboxString = "<input type=\"checkbox\" name=\"item\" value=\"Item 1\" ";
    if (session.getAttribute("checkbox1") != null) { // can't guarantee the method call is correct
        checkboxString += "checked ";
    }
    checkboxString += "> Item 1 <br>";
    Then do the out.println() call with that String.

    Note that this String concatentation should really be done using a StringBuilder, so you might want to read up on that.

  8. #8
    sashi799 is offline Member
    Join Date
    Jul 2010
    Posts
    15
    Rep Power
    0

    Default

    Hi Tolls

    Thanks for the reply. But i got another issue now ..
    Java Code:
     
    ...
    res.sendRedirect(res.encodeRedirectURL("/servletA));
    ...
    this code is suppose to save the session id and send to "servletA" where i can retrieve the session data through
    Java Code:
    req.getSession().getAttribute("string");
    But somehow its not working and returning NULL always. Can u point out where i'm doing it wrong??

  9. #9
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,014
    Rep Power
    20

    Default

    Why don't you forward rather than redirect?

  10. #10
    sashi799 is offline Member
    Join Date
    Jul 2010
    Posts
    15
    Rep Power
    0

    Default

    Java Code:
    if ((req.getParameter("back"))!= null)
    {
    	RequestDispatcher page = req.getRequestDispatcher("/servletA");
    	page.forward(req, res);
    }
    This code also returns NULL in servletA session data.

    But if i put outside the IF statement then the session value is not null but i need it inside the IF since i want to forward only if the BACK button is press. :confused:

  11. #11
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,014
    Rep Power
    20

    Default

    I think you'll need to debug it, because that makes no sense at all.
    Something else must be going on.

    Is there some code on Servlet A that might be deleting/recreating the session?

  12. #12
    sashi799 is offline Member
    Join Date
    Jul 2010
    Posts
    15
    Rep Power
    0

    Default

    Servlet A contains only html ..

    it makes no sense but the issue is with using the submit button. Forwarding works without pressing the back button but it doesnt work when i use the back button .. [what can go wrong in putting the forward code inside an IF stmt]

    Will try converting to JSP and see if it works ....

  13. #13
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,014
    Rep Power
    20

    Default

    Does Servlet B do anything to the session then?

    Do either of them do anything to the session?
    One must since you're saving stuff in there.

  14. #14
    sashi799 is offline Member
    Join Date
    Jul 2010
    Posts
    15
    Rep Power
    0

    Default

    Servlet B
    Java Code:
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    
    
    public class ShowItemList extends HttpServlet
    {
    	
     	public void doPost (HttpServletRequest req, HttpServletResponse res)throws ServletException, IOException 
    	{
    		HttpSession session = req.getSession(true);
    		res.setContentType("text/html");
    		PrintWriter out = res.getWriter();
    		out.println("<HTML><HEAD><TITLE>Welcome</TITLE>");
    		out.println("</HEAD>");
    		out.println("<BODY >");
    		out.println("<br><br>");
    		out.println ("<div align=\"center\"><br>");
    		out.print("<form action=\"");
    		out.print( req.getRequestURI() );
    		out.print("\" method=\"post\">");
    		out.println ("List of the Item :<br><br>");
    		String[] item;
    		item = req.getParameterValues("item");
    		req.getSession().setAttribute("item", item);
    		if (item != null) 
    		{
    			for (int i = 0; i < item.length; i++) 
    			{
    				out.println ((i+1)+"." +item[i]);
    				out.println("<br>");
    			}
    		out.println("<br><br><input type=\"submit\" name=\"buy\" value=\"Buy\">");
    		}
    		else out.println ("<b>none<b>");
    		out.println("&nbsp&nbsp<input type=\"submit\" name=\"back\" value=\"Back\">");
    		out.println("</form>");
    		RequestDispatcher page = getServletContext().getRequestDispatcher("/itemlist");
    		if ((req.getParameter("buy"))!= null)
    		{
    			//code
    		}
    		if ((req.getParameter("back"))!= null)
    		{
    			if (page!=null)
    			{
    				page.forward(req, res);
    			} else {out.println ("<b>request Dispatcher is NULL<b>");}
    		}
    		out.println ("</div>");
    		out.println("</BODY></HTML>");
    	}
    
    	public void doGet (HttpServletRequest req, HttpServletResponse res)throws ServletException, IOException 
    	{
    		doPost(req,res);
    	}
    }
    Servlet A
    Java Code:
    .....
    if (req.getSession().getAttribute("item") != null) 
    		{ 
    			out.println("is not NULL <br><br>");
    			//code
    		}
    		else 
    			out.println ("is NULL<br><br>");
    ....
    Last edited by sashi799; 07-14-2010 at 01:18 PM.

  15. #15
    sashi799 is offline Member
    Join Date
    Jul 2010
    Posts
    15
    Rep Power
    0

    Default

    ok here is another problem.

    Now i can pass the session value but the problem is that once if i have selected the checkbox it always remains checked regardless of whether i unchecked or not.

    i.e. suppose if i select the checkbox in 1st visit then come back to JSP by pressing back from servlet [showin check box as check here] and Deselect/Unchecked the checkbox and go to servlet page [where the data is null as it was uncheck] and press back again but this time also the checkbox is also showing as checked which shouldnt be as i have unchecked it.

    just in short the session value is not changing with selecting / deselecting the checkbox.

    what may be the reason?? i have included the code below. its just a small code for testing.

    JSP code
    Java Code:
    <html>
    	<head>
    		<title>Item List</title>
    	</head>
    
    	<body bgcolor="#fedeab"><br><br><br>
    	<p align=center>
    		<font size=4>
    		Choose the item you want!!!
    	</p>
    	<form action="/demo/showitem" method="post">
    		<%=session.getId()%>
    		<div align=center>
    		<fieldset style="width:250px"> 
    		<legend style="text-align:center">List of item</legend> <br>
    		<%
    			if (session.getAttribute("book1")!=null) {
    		%>
    			<input type="checkbox" name="book1" value="book1" checked > Book 1 <br>
    		<% } else {%>
    			<input type="checkbox" name="book1" value="book1" > Book 1 <br>
    			
    		<% out.println("<br>Session Attribute is NULL <br>"); }%>
    		<input type="submit" value="Enter">
    		</fieldset>
    		</div>
    		
    	</form>
    	</body>
    </html>
    Servlet code
    Java Code:
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    
    
    public class ShowItem extends HttpServlet
    {
    	
     	public void doPost (HttpServletRequest req, HttpServletResponse res)throws ServletException, IOException 
    	{
    		HttpSession session = req.getSession();
    		res.setContentType("text/html");
    		PrintWriter out = res.getWriter();
    		out.println(session.getId());
    		out.println("<br>");
    		out.println("<form>");
    		String book1 = req.getParameter("book1");
    		if (book1 != null)
    		{
    			session.setAttribute("book1",book1);
    		}
    		else
    		{
    			out.println("Request parameter returns NULL");
    			
    		}
    		if (book1 != null)
    		{
    			out.println ("1." + book1 +"<br>");
    			out.println("<br><br><input type=\"submit\" name=\"buy\" value=\"Buy\">");
    		}
    		else
    		{
    			out.println("No item to display<br>");
    		}
    		out.println("&nbsp&nbsp<input type=\"submit\" name=\"back\" value=\"Back\">");
    		
    		RequestDispatcher page = getServletContext().getRequestDispatcher("/jsp/itemlist.jsp");
    		if ((req.getParameter("buy"))!= null)
    		{
    				page.forward(req, res);
    		}
    		if ((req.getParameter("back"))!= null)
    		{
    				page.forward(req, res);
    		}
    		out.println("</form>");
    		
    	}
    
    	public void doGet (HttpServletRequest req, HttpServletResponse res)throws ServletException, IOException 
    	{
    		doPost(req,res);
    	}
    }

  16. #16
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,014
    Rep Power
    20

    Default

    OK.
    First time through, you check the checkbox and hit enter?

    So, in the servlet, it will set the "book1" value in the session. and display the HTML you have (since you already have a JSP I would really recommend creating another one for this stuff).

    Then you click the "back" button of that page, which takes you back to the original JSP, with the checkbox checked. You uncheck the checkbox and hit "enter". Return to the servlet, and then again hit "back".

    Now...where in that flow do you remove the "back1" attribute in the session?

  17. #17
    sashi799 is offline Member
    Join Date
    Jul 2010
    Posts
    15
    Rep Power
    0

    Default

    I have tried using session.removeAtrribute("book1") inside the else stmt of servlets as shown below but in that case the value is not return back to the JSP and if i dont put the removeAtrribute() then the value remains always checked if once checked.

    I have also converted both the code in servlets and its working find there. I just dont know why its not working with the servlets and JSP
    Java Code:
    ...
    if (book1 != null)
    		{
    			session.setAttribute("book1",book1);
    		}
    		else
    		{
                            session.removeAttribute("book1");
    			out.println("Request parameter returns NULL");
    			
    		}
    ...
    Thanks!

  18. #18
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,014
    Rep Power
    20

    Default

    Then I would say your flow is incorrect somewhere.

    You have a starting JSP consisting of the "order" page, with the checkbox.
    This goes to the ShowItem servlet on Enter.
    That servlet should then display the item selected (presumably)...well, to be honest it should forward to the JSP that displays the item. Normally it would get the data from a db, store it in the request and then forward, so mimic that in the servlet.

    That "display" JSP has two buttons, Buy and Back. Each of those does something different, so I would have two more sevlets. Currently, of course, it doesn't look like they do different things, but no harm splitting them out now.

    Back will, therefore, get the value from the session and store it in the request (if it exists), removing the attribute in the session. The original "order" JSP will look in the request for the state of the checkbox.

    I think that's a reasonable flow.

  19. #19
    sashi799 is offline Member
    Join Date
    Jul 2010
    Posts
    15
    Rep Power
    0

Similar Threads

  1. Checkbox value passing to servlet
    By saqib15 in forum New To Java
    Replies: 3
    Last Post: 02-24-2010, 07:20 PM
  2. Replies: 4
    Last Post: 10-19-2009, 11:16 PM
  3. Replies: 7
    Last Post: 10-06-2009, 05:58 AM
  4. Replies: 4
    Last Post: 03-26-2009, 09:42 PM
  5. Replies: 0
    Last Post: 05-22-2008, 10:53 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •