JSP/Servlet | Servlets and JSP/HTML | Passing to JSP and Displaying Results with Forward

Another method is to switch display to the JSP that shows the result by using forward. If a servlet forwards to the JSP that displays the result, the servlet does not need to handle screen display itself.

However, when using this method, you need to consider how to pass result data from the servlet to the forwarded JSP. Let’s explain this while looking at a sample.

hello.jsp

<%@ 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 : <%=request.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="<%=request.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 java.net.URLDecoder;

import javax.servlet.*;
import javax.servlet.http.*;

@SuppressWarnings("serial")
public class MyGaeAppServlet3 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 = URLDecoder.decode(request.getParameter("text1"), "utf8");
        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);
        }
        request.setAttribute("input", param);
        request.setAttribute("result", result);
        ServletContext app = this.getServletContext();
        RequestDispatcher dispatcher = app.getRequestDispatcher("/hello.jsp");
        try {
            dispatcher.forward(request, response);
        } catch (ServletException e) {
            out.println(e);
        }
    }
}

These are the JSP with the form and the servlet source code that receives it. Access hello.jsp, enter an integer in the form, and submit it. It is sent by POST to /mygaeapp and then forwarded back to hello.jsp. At that time, the result calculated by the servlet is displayed as “Result: OO”.

Here, the servlet passes required values to the JSP with the following processing.

Saving values in the servlet

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

Retrieving values in JSP

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

request is an instance of the HttpServletRequest class. By calling the setAttribute method, you can store values inside HttpServletRequest. These can be retrieved at any time with the getAttribute method. The usage of these methods is summarized as follows.

Saving a value

"HttpServletRequest".setAttribute(name, value);

Getting a value

variable = "HttpServletRequest".getAttribute(name);

Now you can store values in HttpServletRequest, or the request. After that, you only need to use forward to switch the display to the JSP. This processing is surprisingly troublesome. It is summarized below.

  1. Get ServletContext
ServletContext app = this.getServletContext();

ServletContext manages the currently running web application. This instance includes important functions of the web application.

  1. Get RequestDispatcher
RequestDispatcher dispatcher = app.getRequestDispatcher("/hello.jsp");

Get an instance named RequestDispatcher from ServletContext. It dispatches the request, meaning it sends it somewhere else. For now, remember that forward is provided as a method in this object.

  1. Forward with the forward method
try {
    dispatcher.forward(request, response);
} catch (ServletException e) {
    out.println(e);
}

Forwarding is executed with the forward method provided by the obtained RequestDispatcher. Specify HttpServletRequest and HttpServletResponse as arguments. These two arguments can simply be the same instances passed as arguments to doGet or doPost.

Forwarding is executed by the forward method, but several instances must be obtained before calling it. You obtain ServletContext and RequestDispatcher, then call the method inside them to execute the forward.