5.1 Facts About JSP

In this section, we will learn the basic facts about JSP.

[!NOTE] The JSP eventually becomes a full-fledged servlet running in your web application[1].

JSP element types (1)

The regular old Java code in JSP is within <% %> tag is called scriptlet. Recall the result.jsp, the importing statement is within <%@ %> tag is called directive. The expression within <%= > is a shorthand for out.println(). Note that there is no semicolon ; in JSP expression.

<%@ page import="java.util.List" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    List<String> books = (List<String>) request.getAttribute("books");
    for (String b : books) {
%>
<%= b %><br>
<% } %>

What about page? You can simply understand it as the directive's scope. For example, <%@ page import="java.util.List" %> means importing java.util.List to current JSP page.

By the way, we can also put comments in the JSP:

<!-- This is an HTML comment. -->
<%-- This is a JSP comment. --%>

Implicit objects

We have used request and out in JSP, and they are indeed implicit objects. For example, the request is a reference to the HttpServletRequest object. The following table summarizes some important mapping from APIs to implicit objects.

APIImplicit Object
JspWriter[2]out
HttpServletRequestrequest
HttpServletResponseresponse
HttpSessionsession
ServletContextapplication
ServletConfigconfig

The following JSP is able to get the attribute from a session, and you can try to output it in ch3/session.

<% String name = (String) session.getAttribute("name"); %>

Expression Language

Scriptlets are considered bad and ugly. There are two big complaints about putting Java code into a JSP:

  • Web page designers and front-end developers should not have to know Java.
  • Java code in a JSP is hard to change and maintain.

To solve this problem, expression language (EL for short) is designed to get rid of Java code. An EL always looks like this: ${something}. In other words, the expression always enclosed in curly braces, and prefixed with a dollar ($) sign. EL is the base of scriptless JSP.

Let's study how to use EL by an example. First, a Book class contains the title and price:

public class Book {
    private String title;
    private float price;
    ...
}

And a User has a favorite book:

public class User {
    private String name;
    private int age;
    private Book favourite;
    ...
}

Then in HelloServlet.java of ch5/el, we add an attribute into request scope. Finally, we forward this request.

Book book = new Book("Gone with the wind", 42.0f);
User user = new User("Mary", 18, book);
request.setAttribute("user", user);
request.setAttribute("name", "Mary");
request.getRequestDispatcher("/WEB-INF/home.jsp").forward(request, response);

Without EL, in order to get data from request's attribute, we have to use scriptlet:

<%
    String name = (String) request.getAttribute("name");
    User user = (User) request.getAttribute("user");
%>
<%= name %>
<%= user.getName() %>

But with EL, it can be simplified dramatically:

${name}
${user.name}

Similarly, we can even get the price of this user's favorite book:

${user.favourite.price}

EL makes it easy to print nested properties. Elegant, isn't it? In the next chapter, we will try to deconstruct EL.

JSP element types (2)

There are five different scripting elements in JSPs, and we have learned four of them in the start of this chapter. Since the declaration element is considered bad and ugly, we won't discuss it.

  • Comment: <%-- --%>
  • Directive: <%@ %>
  • Declaration: <%! %>
  • Scriptlet: <% %>
  • Expression: <%= %>

In what follows, we will study the directive element in depth. Directives supply directions and messages to a JSP container, and these special instructions are used for translating JSP to servlet code. The syntax of directives looks like:

<%@ directive attribute="" %>

There are 3 types of directives: page directive, include directive, and taglib directive.

We have seen the usage of page already. It is used for defining attributes that can be applied to a complete JSP page. In daily programming, import and contentType.

The include directive is used to include one file in another JSP file at translation time[3]. This includes HTML, JSP, text, and other files. It is used to create templates for common UI components, such as headers, footers, and sidebars. For example, footer.html is a sticky footer adapted from Bootstrap:

<footer class="footer mt-auto py-3 bg-light">
    <div class="container">
        <span class="text-muted">Head First Java Web.</span>
    </div>
</footer>

And then we can include it in JSPs:

<%@ include file="foot.html" %>

The JSP taglib directive is implemented to define a tag library with "taglib" as its prefix, and we will learn how to use it in Section 5.3.

One more thing

As we mentioned above, all JSP code will be translated into Servlet code, and this step is done by the container. So, even if there are some mistakes or errors in JSP, they can only be found in the runtime. In addition, your IDA may not be aware of some APIs belonging to javax.servlet.jsp.* (e.g, the implicit object out). For example, your IDE could complain that

Cannot resolve method println(java.lang.String)

<%
out.println("hello world");
%>

But, this error will not cause any bother. If you want to enable the IDE understand those APIs, you can add dependency jsp-api:

compileOnly('javax.servlet.jsp:javax.servlet.jsp-api:2.3.3') {
    exclude group: 'javax.el', module: 'el-api'
    exclude group: 'javax.servlet', module: 'servlet-api'
}

Note that this dependency is totally optional. After all, JSP is an obsolete technology, and we will never focus on its details.


[1] The translated .java and complied .class can be found at work/Catalina folder of Tomcat home under package org.apache.org.

[2] JspWriter is not PrintWriter, but it has most of the same print methods.

[3] The include action tag includes the file at runtime, but we will not cover action tags in this book.