How to remember previously saved form data for subsequent requests

后端 未结 1 1770
北恋
北恋 2021-01-23 12:07

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 r

相关标签:
1条回答
  • 2021-01-23 12:45

    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.
    
    0 讨论(0)
提交回复
热议问题