JSP/Servlet | Servlets and JSP/HTML | Storing Values in the Application

HttpServletRequest and HttpSession have different usable ranges, called scopes. HttpServletRequest exists only while the current request exists. HttpSession always exists while the session is connected. By using these two separately, you can preserve data while considering which range the value should be stored in and maintained for.

In fact, there is another place where values can be stored. It is ServletContext. This class manages the web application itself. Values stored here are preserved and maintained while the web application exists.

The important point is that there is only one ServletContext. HttpServletRequest and HttpSession are prepared for each accessing client. In other words, even if many people use the application at the same time, different objects are prepared for each person and values are stored separately.

ServletContext, however, exists only once per web application. Whoever accesses it accesses the same instance. Therefore, values stored there are the same no matter who accesses them.

Using this, you can easily have data that everyone can share. Let’s try it.

hello.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
        pageEncoding="utf-8"%>
<%@ page import="java.util.ArrayList" %>
<!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;
}
table tr td {
    background: #DDFFDD;
    padding: 2px;
}
</style>
</head>
<body>
    <h1>Hello App Engine!</h1>
    <hr>
    <p id="msg">Message: </p>
    <form method="post" action="/mygaeapp">
    <table>
        <tr>
            <td>Input</td>
            <td><input type="text" id="input" name="text1"></td>
        </tr>
        <tr>
            <td></td>
            <td><input type="submit" value="Send"></td>
        </tr>
    </table>
    </form>
    <hr>
    <table>
    <%
    ArrayList<String> datas = (ArrayList<String>)application.getAttribute("datas");
    if (datas != null){
        for(String str : datas){
            out.println("<tr><td>" + str + "</td></tr>");
        }
    }
    %>
    </table>
</body>
</html>

MyGaeAppServlet.java

package com.devkuma.mygaeapp;

import java.io.*;
import java.util.ArrayList;

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

@SuppressWarnings("serial")
public class MyGaeAppServlet5 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");
        ServletContext application = this.getServletContext();
        ArrayList<String> datas = (ArrayList<String>) application.getAttribute("datas");
        if (datas == null) {
            datas = new ArrayList<String>();
        }
        datas.add(param);
        application.setAttribute("datas", datas);
        response.sendRedirect("/hello.jsp");
    }
}

The example above stores submitted messages in an ArrayList. Try accessing it from several PCs, entering messages, and submitting them. You will see that all data entered by everyone is stored, and the same data is displayed in every browser.

In a servlet, ServletContext is obtained by calling a method prepared on this.

ServletContext application = this.getServletContext();

In JSP, it is even simpler. It is prepared as the implicit object named application, so you can use it as-is.

ServletContext also provides setAttribute and getAttribute methods, so values can be stored and retrieved. Their usage is exactly the same as with HttpServletRequest and similar classes.

By distinguishing the three classes HttpServletRequest, HttpSession, and ServletContext, you can store values in various forms. These are very important when exchanging required values between servlets and JSP. Remember these three as a set.