Servlet and JSP

MRINAL RANJAN
5 min readMar 7, 2021

Servlet

A servlet is a Java programming language class that is used to extend the capabilities of servers that host applications accessed by means of 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 life-cycle 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.

This blog focuses on writing servlets that generate responses to HTTP requests.

Now you may have a question “What is HTTP?”

HTTP is a protocol which allows the fetching of resources, such as HTML documents. It is the foundation of any data exchange on the Web and it is a client-server protocol, which means requests are initiated by the recipient, usually the Web browser. A complete document is reconstructed from the different sub-documents fetched, for instance text, layout description, images, videos, scripts, and more.

Servlet Life Cycle

The life cycle 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.

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.

Invokes the service method, passing request and response objects.

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

Let’s create a simple app which prints “hello” on your browser.

HTTP methods — doGet and doPost

  1. Let’s extend our Servlet class to HttpServlet. This extension allows us to use the doGet method and doPost. Get and Post are common methods of the HTTP to indicate the kind of action that we want. Here are definition of some of the methods commonly used:
  • DELETE — Removes specified resource
  • GET — Fetches data from server
  • POST — Sends data to server
  • PUT — Replaces current representation of target resource with uploaded content

2. If we want to get any data or page we use GET method, we should write our page in the doGet method. When the user wants to send any data we use POST method in which we send data back to server. Hence in the doPost method, we retrieve the data using getParameter method.

package com.hello;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HelloServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

@Override
public void init() throws ServletException {
// Servlet initialization code here
super.init();
}

@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {

// Set response content type
response.setContentType("text/html");

// Actual logic goes here.
PrintWriter out = response.getWriter();
out.println("<h1>Hello</h1>");
}

@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {

}

@Override
public void destroy() {
// resource release
super.destroy();
}
}

Deployment Description (web.xml)

  1. In the index.html form, when we click on submit button and ask for /hello path, we really want to call HelloServlet but our application does not know to do that. Hence we need to link both via deployment description of web.xml.

2. In the web.xml, for every servlet we need to add 2 tags (servlet and servlet-mapping) with 2 sub-tags each.

3. The 2 tags, <servlet> and <servlet-mapping> are bound to each other by a common sub-tag <servlet-name> which can be any name. Hence whenever a /hello path is requested, from the web.xml it will be able to retrieve to correct servlet class which is HelloServlet from the common servlet name tag.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
</web-app>
<servlet>
<servlet-name>servlet</servlet-name>
<servlet-class>com.hello.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>servlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>

How can we redirect our user to a different page?

Our HttpServlet class has 2 ways for that:

  1. RequestDispatcher
  2. sendRedirect

RequestDispatch vs sendRedirect

  1. RequestDispatcher forwards request to another page without going back to client browser whereas sendRedirect goes back to client browser before requesting new url.
  2. Use request.setAttribute to pass data using RequestDispatcher and perform url rewriting using sendRedirect .

JavaServer Pages (JSP)

We can see to build a form in Server, we have to wrap each line of the HTML with PrintWriter but we have to work allot. We can further improve this by using JSP.

JSP which stands for Java Server Pages is an extension of the servlet technology created to support authoring of HTML and XML pages. In MVC model, JSP can be use to represent the view while Servlet is the controller. In JSP, most of the building blocks are in HTML but you can insert Java code blocks whereas for Servlet it is build entirely using Java.

JavaServer Pages (JSP) 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:

  • Coding in JSP is easy :- As it is just adding JAVA code to HTML/XML.
  • Reduction in the length of Code :- In JSP we use action tags, custom tags etc.
  • Connection to Database is easier :-It is easier to connect website to database and allows to read or write data easily to the database.
  • Make Interactive websites :- In this we can create dynamic web pages which helps user to interact in real time environment.
  • Portable, Powerful, flexible and easy to maintain :- as these are browser and server independent.
  • No Redeployment and No Re-Compilation :- It is dynamic, secure and platform independent so no need to re-compilation.
  • Extension to Servlet :- as it has all features of servlets, implicit objects and custom tags

JSP is mainly about adding Java to your webpage’s HTML and it is fairly easy to learn and code.

example:

<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>JSP - Hello World</title>
</head>
<body>
<%
String hello = "Hello";
%>
<h1><%= hello %></h1>
<br/>
</body>
</html>

JSP syntax

Declaration Tag :-It is used to declare variables.

Syntax:- 
<%! Dec variable %>
Example:-
<%! int variable = 10; %>

Java Scriplets :- It allows us to add any number of JAVA code, variables and expressions.

Syntax:- 
<% java code %>

JSP Expression :- It evaluates and convert the expression to a string.

Syntax:- 
<%= expression %>
Example:-
<% num1 = num1+num2 %>
<h1><%= expression %></h1>
  1. JAVA Comments :- It contains the text that is added for information which has to be ignored.
Syntax:- 
<% -- Comments %>

JSP Model Architecture

References

--

--