user1852114
user1852114

Reputation: 51

How to remember previously saved form data for subsequent requests

I have the code below in a servlet (page1) and I want after pressing Save to go to a second servlet (page2), read the content written in the form of page1 and append them in a radio group like this:

Question [i]: question  (i increases every time a question is added in page2)
radiobutton1 (radio1)
radiobutton2 (radio2)
radiobutton3 (radio3)

The point is every time I fill the form below, the data shall be added below data that have been saved previously.

Could you suggest some sample code for servlet page2?

Thanks a lot.

out.println("<form  id=\"form1\" action = \"page2\" method = \"POST\" >");            
        out.println("<input type=\"text\" name=\"question\"><br />");
        out.println("<input type=\"text\" name=\"radio1\"><br />");
        out.println("<input type=\"text\" name=\"radio2\"><br />");
        out.println("<input type=\"text\" name=\"radio3\"><br />");
        out.println("<input type = \"submit\" value = \"Save\">");

Upvotes: 1

Views: 1391

Answers (1)

BalusC
BalusC

Reputation: 1109132

You can use either <input type="hidden"> or the session scope to remember previously saved data. E.g.

<input type="hidden" name="question1answer" value="42" />

or

request.getSession().setAttribute("question1answer", 42);

The passed data is the subsequent request available as

String question1answer = request.getParameter("question1answer");

or

Integer question1answer = (Integer) request.getSession().getAttribute("question1answer");

The disadvantage of hidden inputs is that it produces quite some boilerplate code and that the enduser can easily guess/manipulate it. The disadvantage of the session scope is that it's shared across all requests within the same session (and thus may interfere when the enduser has the same page open in multiple browser windows/tabs). To combine best of both worlds, you can on 1st request generate a long and unique key which you use as a key to store all the associated data in the session scope and pass that key as hidden request parameter.

E.g. in first request

String key = UUID.randomUUID().toString();
request.setAttribute("key", key);
List<Answer> answers = new ArrayList<Answer>();
request.getSession().setAttribute(key, answers);
// ...
answer.add(question1answer);

and in HTML

<input type="hidden" name="key" value="${key}" />

and in all subsequent requests

String key = request.getParameter("key");
request.setAttribute("key", key);
List<Answer> answers = (List<Answer>) request.getSession().getAttribute(key);
// ...
answers.add(question2answer); // question3answer, question4answer, etc.

Upvotes: 2

Related Questions