JSP/Servlet | Servlets and JSP/HTML | Displaying Results with Redirect

With forward, the address shown in the browser’s URL bar does not change, so the contents of hello.jsp are displayed while the address still remains /mygaeapp. This is not a major problem, but if you reload, the servlet’s doGet output will be displayed.

To properly return the address to hello.jsp, you need to use redirect instead of forward. However, when using redirect, you must pass values in a different way from forward.

The example that previously used forward is modified below to use redirect.

<%@ page language="java" contentType="text/html; charset=utf-8"
        pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Sample jsp</title>
<style>
h1{
    font-size: 16pt;
    background: #AAFFAA;
    padding: 5px;
}
</style>
</head>
<body>
    <h1>Hello App Engine!</h1>
    <p>Result :  <%=session.getAttribute("result") %></p>
    <hr>
    <p id="msg">Enter an integer: </p>
    <form method="post" action="/mygaeapp">
    <table>
        <tr>
            <td>Input</td>
            <td><input type="text" id="input" name="text1" value="<%=session.getAttribute("input") %>"></td>
        </tr>
        <tr>
            <td></td>
            <td><input type="submit" value="Send"></td>
        </tr>
    </table>
    </form>
</body>
</html>

MyGaeAppServlet.java

package com.devkuma.mygaeapp;

import java.io.*;

import javax.servlet.http.*;

@SuppressWarnings("serial")
public class MyGaeAppServlet4 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/plain");
        request.setCharacterEncoding("utf8");
        response.setCharacterEncoding("utf8");
        PrintWriter out = response.getWriter();
        out.println("Hello, world!");
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html");
        request.setCharacterEncoding("utf8");
        response.setCharacterEncoding("utf8");
        String param = request.getParameter("text1");
        PrintWriter out = response.getWriter();
        int result = 0;
        try {
            int n = Integer.parseInt(param);
            for (int i = 1; i <= n; i++) {
                result += i;
            }
        } catch (NumberFormatException e) {
            out.println(e);
        }
        HttpSession session = request.getSession();
        session.setAttribute("input", param);
        session.setAttribute("result", result);
        response.sendRedirect("/hello.jsp");
    }
}

Try running this. When you submit the form, it returns to the form display and the calculated sum is shown. At this time, the URL address correctly returns to hello.jsp. Now reloading does not cause a problem.

Redirect is easier to use than forward. You only need to call the following method.

"HttpServletResponse".sendRedirect(redirectAddress);

It is very simple compared with forward. Just specify the redirect address as the argument. However, when using redirect, the destination cannot receive values passed with HttpServletRequest’s setAttribute.

HttpServletRequest manages the request. With forward, only the displayed content on the server changes, so the request is not interrupted. But redirect uses HTTP header information to move the browser to the specified page. In other words, when the browser moves to another page based on the received header information, the request ends. Therefore, HttpServletRequest disappears there, and a new HttpServletRequest is provided again. So even if you store values in the request with setAttribute, you cannot retrieve them.

What should you do, then? The mechanism for this situation is the session. We used sessions a little in JSP as well. A session is a structure for maintaining a continuous connection between the server and client.

This session is provided as the HttpSession class. It can be obtained from request.

HttpSession session = request.getSession();

By calling getSession on the HttpServletRequest instance in the request, you can obtain the HttpSession instance that manages the current session. Then call setAttribute on this instance to store values in the session.

session.setAttribute("input", param);
session.setAttribute("result", result);

After that, change the part that gets values on the JSP side from request to session. It looks like this. In JSP, HttpSession can be used as the implicit object named session.

<%= session.getAttribute("result") %>
<%= session.getAttribute("input") %>

Because the session remains even after the request passes, values can be retrieved properly even in the redirected JSP. With this, you can move pages safely.