Retaining the submitted JSP form data

java, jsp, servlets

Solution

Best what you can do is to submit to your own servlet which in turn fires another request to the external webapplication in the background with little help of `java.net.URLConnection`. Finally just post back to the result page within the same request, so that you can just access request parameters by EL. There's an implicit EL variable `${param}` which gives you access to the request parameters like a `Map` wherein the parameter name is the key.

So with the following form

<form action="myservlet" method="post">
    <input type="text" name="foo">
    <input type="text" name="bar">
    <input type="submit">
</form>

and roughly the following servlet method

protected void doPost(HttpServletRequest request, HttpServletResponse response) {
    String foo = request.getParameter("foo");
    String bar = request.getParameter("bar");

    String url = "http://external.com/someapp";
    String charset = "UTF-8";
    String query = String.format("foo=%s&bar=%s", URLEncoder.encode(foo, charset), URLEncoder.encode(bar, charset));

    URLConnection connection = new URL(url).openConnection();
    connection.setUseCaches(false);
    connection.setDoOutput(true); // Triggers POST.
    connection.setRequestProperty("accept-charset", charset);
    connection.setRequestProperty("content-type", "application/x-www-form-urlencoded;charset=" + charset);

    try (OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), charset)) {
        writer.write(query);
    }

    InputStream result = connection.getInputStream();
    // Do something with result here? Check if it returned OK response?

    // Now forward to the JSP.
    request.getRequestDispatcher("result.jsp").forward(request, response);
}

you should be able to access the input in `result.jsp` as follows

<p>Foo: <c:out value="${param.foo}" /></p>
<p>Bar: <c:out value="${param.bar}" /></p>

Simple as that. No need for `jsp:useBean` and/or nasty scriptlets.

Problem

I am having a web form(JSP) which submits the data to different application, hosted on different server. After submitting the form data, that application redirect back to same JSP page. Now, I want to save the entered the data. What are the different approaches to retain the submitted data in web form. I would not prefer to store the data in DB or any file. PS: I would like to retain the submitted form data when request again redirected to same JSP page. Therefore, user need not to re-enter the data. Like, data can be stored in Session or Request etc.

Original source