Implicit objects in JSPs

In this part of the JEE tutorials, we will talk about implicit objects in JSP pages. Implicit objects are important objects that are available within scriptlets.

The out object

Implicit object out is used to write to the output stream. The out object has page scope. A specific out object is available for each JSP page.

index.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.util.List" %>
<%@page import="java.util.ArrayList" %>
<!DOCTYPE html>
<html>
  <head>
      <title>Implicit out object</title>
      <style>
          td { border: 1px solid #ccc; padding: 3px }
          th { border: 1px solid #4B8699; padding: 3px; 
              background: #4B8699; color: white }
      </style>
  </head>
  <body>
      <h2>The out object</h2>

      <%!
          List authors = new ArrayList();
      %>

      <%
          if (authors.isEmpty()) { 
            authors.add("Leo Tolstoy");
            authors.add("Fiodor Dostoevsky");
            authors.add("Emile Zola");
            authors.add("Honore de Balzac");
          }

          out.println("<table>");
          out.println("<th>");
          out.println("Authors");
          out.println("</th>");

          for (int i = 0; i < authors.size(); i++) {
              out.println("<tr>");
              out.println("<td>");
              out.println(authors.get(i));
              out.println("</td>");
              out.println("</tr>");
          }
          
          out.println("</table>");
      %>

  </body>
</html>

Our code example creates an HTML table. It uses the implicit out parameter. Note that the example demonstrates the usage of the out object; however, using it in the above way is discouraged.

out.println("<th>");
out.println("Authors");
out.println("</th>");

This code prints a header for the table.

There is another way, how we can print the table—by mixing HTML and Java code.

Note that this way is even more problematic that the previous one. This practice leads to so called Spaghetti code, which is error prone and hard to maintain. JSP scripting should be used sparingly, only when necessary. It is recommended to use JSTL instead.

index.jsp
<%@page contentType="text/html" pageEncoding="UTF-8" %>
<%@page import="java.util.List" %>
<%@page import="java.util.ArrayList" %>
<!DOCTYPE html>
<html>
    <head>
        <title>Implicit out object</title>
        <style>
            td { border: 1px solid #ccc; padding: 3px }
            th { border: 1px solid #4B8699; padding: 3px; 
                 background: #4B8699; color: white }
        </style>
    </head>
    <body>
        <h2>The out object</h2>

        <%!
            List authors = new ArrayList();
        %>

        <%
            if (authors.isEmpty()) {
                authors.add("Leo Tolstoy");
                authors.add("Fiodor Dostoevsky");
                authors.add("Emile Zola");
                authors.add("Honore de Balzac");
            }
        %>

        <table>
            <th>Authors</th>

            <% for (int i = 0; i < authors.size(); i++) { %>
            <tr>
                <td>
                    <%= authors.get(i) %>
                </td>
            </tr>
            <% } %>

        </table>

    </body>
</html>

The outcome is the same for both examples.

Implicit out object
Figure: Implicit out object

The response object

The response object is used as a reply to the request from the client. This object is seldom used by JSP authors. The response object has page scope. There is one situation, where the response object might be useful. Say we want to rename the URL of one page. But we realize that many people might have bookmarked the page. To overcame this issue, we might use the response object to redirect the request to a new page.

index.jsp
<%
  response.sendRedirect("target.jsp");
%>

We use the sendRedirect() method to redirect to a different JSP page.

target.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Target JSP page</title>
    </head>
    <body>
        <h2>Welcome</h2>
    </body>
</html>

When we run the example, we end up with the target.jsp page.

The request object

We will demonstrate a request object in a simple form. The form is use to send user data to the server for processing.

index.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Book name</title>
    </head>
    <body>
        <form method="get" action="book.jsp">
            <label for="bookname"> Enter a book name:</label>            
            <input type="text" name="bookname" id="bookname">                        
            <input type="submit" value="submit">
        </form>
    </body>
</html>

In the index.jsp file, we define a simple HTML form.

book.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Book name</title>
    </head>
    <body>
        <p>
            You have entered: <%= request.getParameter("bookname")%>
        </p>
    </body>
</html>

In this example, we have two JSP files. The first file is used to enter data. he data is sent to the second JSP file, which will simply print the data, we have entered.

<form method="get" action="book.jsp">

The action parameter specifies the name of the JSP file, which will receive the data we send.

You have entered: <%= request.getParameter("bookname") %>

This line will output the data we entered into the form. The request object encapsulates the data sent by the client.

Next we use an alternative method to deploy the WAR file.

$ ls
books.jsp  index.jsp

We have two JSP files.

$ jar -cvf form.war *
added manifest
adding: books.jsp(in = 335) (out= 200)(deflated 40%)
adding: index.jsp(in = 514) (out= 251)(deflated 51%)

We create a web archive.

$ ls
books.jsp  form.war  index.jsp

The web archive has been created.

$ asadmin deploy --user=admin ~/programming/jee/form/form.war

We can use the asadmin tool to deploy the web archive. We provide the user name and the path to the WAR file. By default, the admin user is called admin and the password is adminadmin.

Command deploy executed successfully.

If everything goes ok, we see this message.

The application object

The application object is available to all clients. It shares data on all application pages. The application object can be used to share data, log messages, track user hits, or access server information.

index.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h2>Application object</h2>

        <p>
            Resource paths:
        </p>

        <%= application.getResourcePaths("/")%> <br>
        <%= application.getResourcePaths("/WEB-INF")%><br>
        <%= application.getResourcePaths("/META-INF")%>

        <p>
            Server: <%= application.getServerInfo()%>
        </p>

        <p>
            Context path:<%= application.getContextPath()%>
        </p>

    </body>
</html>

In our example, we print resource paths. These are all paths to resources within the web application. Further we print server information and the context path. Our server is Apache Tomcat. The context path uniquely identifies the web application in server.

Application object
Figure: Application object

In this chapter, we mentioned JSP implicit objects.