Introduction to Servlets and JSP

Dasari Swaroop Kumar
12 min readDec 6, 2020

In this article, I will discuss enough content to make you understand concepts in both Servlets and JSP.

1. 1 Servlet Introduction

A servlet is a Java programming language class used to extend the capabilities of servers that host applications accessed using a request-response programming model. Although servlets can respond to any type of request, they are commonly used to extend the applications hosted by web servers. For such applications, Java Servlet technology defines HTTP-specific servlet classes.

The javax.servlet and javax.servlet.http packages provide interfaces and classes for writing servlets. All servlets must implement the Servlet interface, which defines lifecycle methods. When implementing a generic service, you can use or extend the GenericServlet class provided with the Java Servlet API. The HttpServlet class provides methods, such as doGet and doPost, for handling HTTP-specific services.

1.2 Servlet Lifecycle

The lifecycle of a servlet is controlled by the container in which the servlet has been deployed. When a request is mapped to a servlet, the container performs the following steps.

  1. If an instance of the servlet does not exist, the web container:
  • Loads the servlet class
  • Creates an instance of the servlet class.
  • Initializes the servlet instance by calling the init method.

2. The container invokes the service method, passing request and response objects.

If it needs to remove the servlet, the container finalizes the servlet by calling the servlet’s destroy method.

1.3 Creating and Initializing a Servlet

Use the @WebServlet annotation to define a servlet component in a web application. This annotation is specified on a class and contains metadata about the servlet being declared. The annotated servlet must specify at least one URL pattern. This is done by using the urlPatterns or value attribute on the annotation.

Classes annotated with @WebServlet must extend the javax.servlet.http.HttpServlet class. For example, the following code snippet defines a servlet with the URL pattern /report:

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
@WebServlet("/report")
public class MoodServlet extends HttpServlet {
...

The web container initializes a servlet after loading and instantiating the servlet class and before delivering requests from clients. To customize this process to allow the servlet to read persistent configuration data, initialize resources, and perform any other one-time activities, you can either override the init method of the Servlet interface or specify the initParams attribute of the @WebServlet annotation. The initParams attribute contains a @WebInitParam annotation. If it cannot complete its initialization process, a servlet throws an UnavailableException.

1.4 Writing Service Methods

The service provided by a servlet is implemented in the service method of a GenericServlet, in the doMethod methods (where Method can take the value Get, Delete, Options, Post, Put, or Trace) of an HttpServlet object, or in any other protocol-specific methods defined by a class that implements the Servlet interface. The term service method is used for any method in a servlet class that provides a service to a client.

For HTTP servlets, the correct procedure for populating the response is to do the following:

  1. Retrieve an output stream from the response.
  2. Fill in the response headers.
  3. Write any body content to the output stream.

Response headers must always be set before the response has been committed. The web container will ignore any attempt to set or add headers after the response has been committed. The next two sections describe how to get information from requests and generate responses.

1.4.1 Getting Information from Requests

A request contains data passed between a client and the servlet. All requests implement the ServletRequest interface. This interface defines methods for accessing the following information:

  • Parameters, which are typically used to convey information between clients and servlets
  • Object-valued attributes, which are typically used to pass information between the web container and a servlet or between collaborating servlets
  • Information about the protocol used to communicate the request and about the client and server involved in the request
  • Information relevant to localization

The request path is further composed of the following elements.

  • Context path: A concatenation of a forward slash (/) with the context root of the servlet's web application.
  • Servlet path: The path section that corresponds to the component alias that activated this request. This path starts with a forward slash (/).
  • Path info: The part of the request path that is not part of the context path or the servlet path.

You can use the getContextPath, getServletPath, and getPathInfo methods of the HttpServletRequest interface to access this information. Except for URL encoding differences between the request URI and the path parts, the request URI is always comprised of the context path plus the servlet path plus the path info.

Query strings are composed of a set of parameters and values. Individual parameters are retrieved from a request by using the getParameter method.

1.4.2 Constructing Responses

A response contains data passed between a server and the client. All responses implement the ServletResponse interface. This interface defines methods that allow you to do the following.

  • Retrieve an output stream to use to send data to the client. To send character data, use the PrintWriter returned by the response's getWriter method.
  • Indicate the content type (for example, text/html) being returned by the response with the setContentType(String) method. This method must be called before the response is committed.

HTTP response objects, javax.servlet.http.HttpServletResponse, have fields representing HTTP headers, such as the following.

  • Status codes, which are used to indicate the reason a request is not satisfied or that a request has been redirected.
  • Cookies, which are used to store application-specific information at the client. Sometimes, cookies are used to maintain an identifier for tracking a user’s session.

1.5 Filtering Requests and Responses

A filter is an object that can transform the header and content (or both) of a request or response. Filters differ from web components in that filters usually do not themselves create a response. Instead, a filter provides functionality that can be “attached” to any kind of web resource.

The main tasks that a filter can perform are as follows.

  • Query the request and act accordingly.
  • Block the request-and-response pair from passing any further.
  • Modify the request headers and data. You do this by providing a customized version of the request.
  • Modify the response headers and data. You do this by providing a customized version of the response.
  • Interact with external resources.

1.5.1 Programming Filters

The filtering API is defined by the Filter, FilterChain, and FilterConfig interfaces in the javax.servlet package. You define a filter by implementing the Filter interface.

Use the @WebFilter annotation to define a filter in a web application. This annotation is specified on a class and contains metadata about the filter being declared. The annotated filter must specify at least one URL pattern. This is done by using the urlPatterns or value attribute on the annotation.

To add configuration data to the filter, specify the initParams attribute of the @WebFilter annotation. The initParams attribute contains a @WebInitParam annotation. The following code snippet defines a filter, specifying an initialization parameter:

import javax.servlet.Filter;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
@WebFilter(filterName = "TimeOfDayFilter",
urlPatterns = {"/*"},
initParams = {
@WebInitParam(name = "mood", value = "awake")})
public class TimeOfDayFilter implements Filter {
...

The most important method in the Filter interface is doFilter, which is passed the request, response, and filter chain objects. This method can perform the following actions.

  • Examine the request headers.
  • Customize the request object if the filter wishes to modify request headers or data.
  • Customize the response object if the filter wishes to modify response headers or data.
  • Invoke the next entity in the filter chain. The filter invokes the next entity by calling the doFilter method on the chain object, passing in the request and response it was called with or the wrapped versions it may have created. Alternatively, the filter can choose to block the request by not making the call to invoke the next entity.
  • Examine response headers after invoking the next filter in the chain.
  • Throw an exception to indicate an error in processing.

In addition to doFilter, you must implement the init and destroy methods. The init method is called by the container when the filter is instantiated. If you wish to pass initialization parameters to the filter, you retrieve them from the FilterConfig object passed to init.

1.6 Maintaining Client State

Many applications require that a series of requests from a client be associated with one another. For example, a web application can save the state of a user’s shopping cart across requests. Web-based applications are responsible for maintaining such a state, called a session, because HTTP is stateless. To support applications that need to maintain state, Java Servlet technology provides an API for managing sessions and allows several mechanisms for implementing sessions.

1.6.1 Accessing a Session

Sessions are represented by an HttpSession object. You access a session by calling the getSession method of a request object. This method returns the current session associated with this request; or, if the request does not have a session, this method creates one.

1.6.2 Associating Objects with a Session

You can associate object-valued attributes with a session by name. Such attributes are accessible by any web component that belongs to the same web context and is handling a request that is part of the same session.

1.6.3 Session Management

Because an HTTP client has no way to signal that it no longer needs a session, each session has an associated timeout so that its resources can be reclaimed. The timeout period can be accessed by using a session’s getMaxInactiveInterval and setMaxInactiveInterval methods.

  • To ensure that an active session is not timed out, you should periodically access the session by using service methods because this resets the session’s time-to-live counter.
  • When a particular client interaction is finished, you use the session’s invalidate method to invalidate a session on the server-side and remove any session data.

1.6.4 Session Tracking

To associate a session with a user, a web container can use several methods, all of which involve passing an identifier between the client and the server. The identifier can be maintained on the client as a cookie, or the web component can include the identifier in every URL that is returned to the client.

If your application uses session objects, you must ensure that session tracking is enabled by having the application rewrite URLs whenever the client turns off cookies. You do this by calling the response’s encodeURL(URL) method on all URLs returned by a servlet. This method includes the session ID in the URL only if cookies are disabled; otherwise, the method returns the URL unchanged.

2.1 JavaServer Pages Technology:

JavaServer Pages (JSP) technology allows you to easily create web content that has both static and dynamic components. JSP technology makes available all the dynamic capabilities of Java Servlet technology but provides a more natural approach to creating static content.

The main features of JSP technology are as follows:

  • A language for developing JSP pages, which are text-based documents that describe how to process a request and construct a response.
  • An expression language for accessing server-side objects.
  • Mechanisms for defining extensions to the JSP language.

What Is a JSP Page?

A JSP page is a text document that contains two types of text: static data, which can be expressed in any text-based format, and JSP elements, which construct dynamic content.

The recommended file extension for the source file of a JSP page is .jsp. The page can be composed of a top file that includes other files that contain either a complete JSP page or a fragment of a JSP page. The recommended extension for the source file of a fragment of a JSP page is .jspf.

The JSP elements in a JSP page can be expressed in two syntaxes, standard and XML, though any given file can use only one syntax. A JSP page in XML syntax is an XML document and can be manipulated by tools and APIs for XML documents.

Here’s a sample JSP code,

<%@page language="java" contentType="text/html" pageEncoding="UTF-8" %>
<!DOCTYPE HTML >
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Echoing HTML Request Parameters</title>
</head>

<body>
<h2>Choose authors:</h2>
<form method="get">
<input type="checkbox" name="author" value="Tan Ah Teck">Tan
<input type="checkbox" name="author" value="Mohd Ali">Ali
<input type="checkbox" name="author" value="Kumar">Kumar
<input type="checkbox" name="author" value="Peter Johnson">Peter
<input type="submit" value="Query">
</form>

<%
String[] authors = request.getParameterValues("author");
if (authors != null) {
%>
<h3>You have selected author(s):</h3>
<ul>
<%
for (String author : authors) {
%>
<li><%= author %></li>
<%
}
%>
</ul>
<%
}
%>
<br /><a href="<%= request.getRequestURI() %>">BACK</a>
<body>
</html>

Run the JSP page and study the generated servlet.

Explanation:

  • This page has an HTML form with 4 checkboxes, identified by their “name=value" pairs of "author=xxx". No "action" attribute is specified in the <form> tag. The default "action" is the current page (i.e. the query will be sent to the same page for processing).
  • The JSP scriptlet checks if the query parameter “author" exists. For the first request, "author" parameter is absent. Once the user fills in and submits the form, "author" will be present in the HTTP request.
  • request.getParameterValues() is used to retrieve all the values of the query parameter "author". The values are echoed back to the client in an unordered list.

2.2 JSP Scripting Elements

JSP scripting elements are enclosed within <% ...... %>, similar to other server-side scripts such as ASP and PHP. To print <%, use escape sequence <\%.

JSP Comment <% — comments — %>

JSP comments <%-- JSP comments --%> are ignored by the JSP engine. For example,

<%-- anything but a closing tag here will be ignored -->

Note that HTML comment is <!-- html comments -->. JSP expression within the HTML comment will be evaluated. For example,

<!-- HTML comments here <%= Math.random() %> more comments -->

JSP Expression <%= JavaExpression %>

A JSP expression is used to insert the resultant value of a single Java expression into the response message. The Java expression will be placed inside a out.print(...) method. Hence, the expression will be evaluated and the resultant value printed out as part of the response message. Any valid Java expression can be used. There is no semi-colon at the end of the expression.

For examples:

<%= Math.sqrt(5) %>
<%= item[10] %>
<p>The current data and time is: <%= new java.util.Date() %></p>

The above JSP expressions will be converted to:

out.print( Math.sqrt(5) );
out.print( item[10] );
out.write("<p>Current time is: ");
out.print( new java.util.Date() );
out.write("</p>");

You can use the pre-defined variables in the expressions. For examples:

<p>You have choose author <%= request.getParameter("author") %></p>
<%= request.getRequestURI() %>

You can also use the XML-compatible syntax of <jsp:expression>Java Expression</jsp:expression>.

JSP Scriptlet <% Java Statements %>

JSP scriptlets allow you to implement more complex programming logic. You can use scriptlets to insert any valid Java statements into the _jspService() method of the translated servlet. The Java codes must be syntactically correct, with Java statements terminated by a semi-colon.

For example:

<%
String author = request.getParameter("author");
if (author != null && !author.equals(""))) {
%>
<p>You have choose author <%= author %></p>
<%
}
%>

In the translated servlet, the above will be inserted into the service() method as follows:

public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
......
String author = request.getParameter("author");
if (author != null && !author.equals(""))) {
out.write("<p>You have choose author ");
out.print(author);
out.write("</p>");
}
}

The source codes of scriptlets are only available in the server, and not sent to the client. That is, scriptlets are safe and secure!

You can also use the XML-compatible syntax of <jsp:scriptlet>Java Statements</jsp:scriptlet>.

JSP Declaration <%! Java Statements %>

JSP declarations can be used to define variables and methods for the class. Unlike scriptlets that are inserted inside the _jspService() method, the declaration codes are inserted inside the class, at the same level as _jspService(), as variables or methods of the class.

For example,

<%! private int count; %>
<%! public int incrementCount() { ++count; } %>

will be translated to:

public final class first_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {

private int count;
public int incrementCount() { ++count; }

public void _jspInit() { ...... }

public void _jspDestroy() { ...... }
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, ServletException { ...... }
}

You can also use the XML-compatible syntax of <jsp:declaration>Java Statements</jsp:declaration>.

JSP Directive <%@ … %>

JSP directives provide instructions to the JSP engine to aid in the translation. The syntax of the JSP directive is:

<%@ directiveName attribute1="attribute1value" attribute2="attribute2value" ... %>

The directives include: page, include, taglib.

JSP Page Directive <%@page … %>

Typically, a JSP file starts with the page directive:

<%@page language="java" contentType="text/html" %>

The “page import" directive lets you, import classes. The syntax is:

<%@page import="packageName.*" %>
<%@page import="packageName.className" %>
<%@page import="packageName.className1, packageName.className2,..." %>

This directive generates proper import statements at the top of the servlet class. User-defined classes must be stored in “webContextRoot\WEB-INF\classes", and kept in a proper package (default package not allowed).

For example,

<%-- import package java.sql.* --%>
<%@page import="java.sql.*" %>

<%-- import a user-defined class --%>
<%@page import="mypkg.myClass1, mypkg.myClass2" %>

The “page" directives are also used to set the MIME type, the character set of the response message. This information will be written to the response message's header. For example,

<%-- Set the response message's MIME type, character set --%>
<%@page contentType="image/gif" %>
<%@page contentType="text/html" charset="UTF-8" %>
<%@page pageEncoding="UTF-8" %>

<%-- Set an information message for getServletInfo() method --%>
<%@page info="Hello world example" %>

The “page session" directive allows you to designate whether this page belongs to the session. The default is "true". Setting to "false" could reduce the server's load if session tracking is not needed in your application.

<%@page session="true|false" @>

Other “page" directives include: errorPage, isErrorPage, buffer, isThreadSafe, isELIgnored, etc.

JSP Include Directive <%@include … %>

The “include" directive lets you insert the unprocessed content of an external file. You can include any JSP files or static HTML files. You can use include directive to include the navigation bar, copyright statement, logo, etc. on every JSP page. The syntax is:

<%@include file="url" %>
<%@include page="url" &>

If another JSP page is included using “include file", the JSP engine will not check for an update of the included JSP file during execution.

For example:

<%@include file="header.jsp" %>
....
<%@include file="footer.jsp" %>

JSP Taglib Directive <%@taglib ... %>

JSP allows you to create your own libraries of JSP tags. You can use the taglib directive to tell Tomcat what libraries to load and where they are. For example,

<%@taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

That’s all for now in this article, catch you guys in the next one!

--

--