Chapter 5: JSP And Scriptless JSP

In this chapter, we will focus on JSP. In previous chapters, we have used JSP for many times. In particular, JSP mainly works as a view. Basically, an inaccurate definition of JSP can be an HTML page enhanced by Java. The following code is from home.jsp:

<h1>Cover your page.</h1>
<%
String name = (String) request.getAttribute("name");
%>
<p class="lead">Hello <%= name %></p>

As we can see, JSP can combine HTML tags and regular Java code, as well as its extending syntax (e.g., JSP expression tag). Although you can do many things in JSP, keep in mind that the right role of JSP is just being a view, nothing more. So importantly, you will learn what not to write in JSP. To put it in another way, there are good, bad and ugly in JSP[1], and we only need to concentrate on the good. For example, writing Java code in JSP is considered bad, so scriptless JSP using tag expressions is preferred.

As a matter of fact, a JSP is also a servlet, and the container would translate it into Java source code, and complies it into a full-fledged Java servlet class. Sound a bit complicate, right? Those abstruse parts are bad and ugly, so it is okay to ignore them.

[!TIP] Learning JSP is somewhat in vain, so we only study its good parts.

Currently, JSP is generally considered obsolete, and many modern alternatives (e.g., Thymeleaf) become incredibly popular. However, there are still some reasons to learn it in 2022:

  • Understanding JSP's good part will help you learn other alternatives.
  • JSP is a part of Java EE, while other alternatives are third parties.
  • You may have to maintain some legacy projects which are written in JSP.

[1] The Good, the Bad and the Ugly is a 1966 Italian epic spaghetti Western film directed by Sergio Leone.