Servlet and JSP

Abhinav Kumar gupta
5 min readDec 7, 2020

Servlet is a simple java program that runs on a server and capable of handling requests and generating dynamic responses. Servlet has the capability to change the site contents according to the time or are able to generate the contents according to the request received by the client.

Advantages of using Servlets

  • Less response time because each request runs in a separate thread.
  • Servlets are scalable.
  • Servlets are robust and object-oriented.
  • Servlets are platform-independent.
  • Servlets work on the server-side.
  • Servlets are capable of handling complex requests obtained from the webserver.
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

// Extend HttpServlet class
public class HelloWorld extends HttpServlet {

private String message;

public void init() throws ServletException {
// Do required initialization
message = "Hello World";
}

public 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>" + message + "</h1>");
}

public void destroy() {
// do nothing.
}
}

JSP stands for Java Server Pages. It is a server-side technology, that is used to create dynamic web content. It is the extension of the servlet that provides more functionality than servlet such as expression language, JSTL, etc. JSP tags are used to insert JAVA code into HTML pages. In JSP, Java code can be inserted in HTML/ XML pages or both. JSP is first converted into a servlet by JSP container before processing the client’s request.

<%-- JSP comment --%>
<HTML>
<HEAD>
<TITLE>MESSAGE</TITLE>
</HEAD>
<BODY>
<%out.print("Hello, Sample JSP code");%>
</BODY>
</HTML>

Advantages of using JSP

  • It does not require advanced knowledge of JAVA.
  • It is capable of handling exceptions.
  • Easy to use and learn.
  • It can tags which are easy to use and understand.
  • Implicit objects are there which reduces the length of code.
  • It is suitable for both JAVA and non-JAVA programmer.

Disadvantages of using JSP

  • Difficult to debug for errors.
  • First-time access leads to wastage of time.
  • Its output is HTML which lacks features.

There are two ways to add Java code to a .jsp. First, we can use basic Java Scriptlet syntax which involves placing Java code blocks within two Scriptlet tags:

<% Java code here %>

The second method is specific to XML:

<jsp:scriptlet>
Java code here
</jsp:scriptlet>

Importantly, one can use conditional logic clientside with JSP by using if, then, and else clauses and then wrapping the relevant blocks of markup with those brackets.

<% if (doodad) {%>
<div>Doodad!</div>
<% } else { %>
<p>Hello!</p>
<% } %>

To choose between servlet and JSP I use a simple rule: if the page contains more HTML code than java code, go for JSP, otherwise, just write a servlet. In general, that translates roughly to: use JSPs for content presentation and servlets for control, validation, etc. It's easier to organize and structure your code inside a servlet since it uses the plain java class syntax. JSPs tend to be more monolithic, although it's possible to create methods inside them.

Difference Between JSP and Servlet

Java Server Pages is a server-side programming technology that allows the creation of a dynamic, platform-independent method for developing Web-based applications. JSP have access to the whole family of Java APIs, including the JDBC API to access enterprise databases. JavaServer Pages is a technology for creating Web pages that support dynamic content. This helps programmers embed java code in HTML pages by making use of specific JSP tags, most of which begin with <% and end with %>. Servlets implement a component-based, platform-independent method for developing Web-based applications, without the performance restrictions of CGI programs. Servlets have access to the complete family of Java APIs, including the JDBC API to access enterprise databases. Servlets are platform-independent because they have drafted in Java.Java security manager on the server implements a set of limitations to preserve the resources on a server machine.

Servlet Life Cycle

  1. Loading Servlet Class: A Servlet class is loaded when the first request for the servlet is received by the Web Container.
  2. Servlet instance creation: After the Servlet class is loaded, the Web Container creates the instance of it. Servlet instance is created only once in the life cycle.
  3. Call to the init() method: init() method is called by the Web Container on servlet instance to initialize the servlet.
  4. Call to the service() method: The containers call the service() method each time the request for a servlet is received. The service() method will then call the doGet()or doPost() method based on type of HTTP request.
  5. Call to destroy() method: The Web Container call the destroy() method before removing the servlet instance, giving it a chance for cleanup.

The life cycle of JSP Page

JSP life cycle is also managed by the container. Usually, every web container that contains a servlet container also contains a JSP container for managing JSP pages.

JSP pages life cycle phases are:

  • Translation — JSP pages don’t look like normal java classes, actually, the JSP container parses the JSP pages and translates them to generate corresponding servlet source code. If the JSP file name is home.JSP, usually named as home_jsp.java.
  • Compilation — If the translation is successful, then the container compiles the generated servlet source file to generate a class file.
  • ClassLoading — Once JSP is compiled as servlet class, its lifecycle is similar to servlet and it gets loaded into memory.
  • Instance Creation — After the JSP class is loaded into memory, its object is instantiated by the container.
  • Initialization — The JSP class is then initialized and it transforms from a normal class to a servlet. After initialization, ServletConfig and ServletContext objects become accessible to the JSP class.
  • Request Processing — For every client request, a new thread is spawned with ServletRequest and ServletResponse to process and generate the HTML response.
  • Destroy — The last phase of the JSP life cycle where it’s unloaded into memory.

Life cycle methods of JSP

JSP lifecycle methods are:

  1. jspInit() declared in JspPage interface. This method is called only once in JSP lifecycle to initialize config params.
  2. _jspService(HttpServletRequest request, HttpServletResponse response) declared in HttpJspPage interface and response for handling client requests.
  3. jspDestroy() declared in JspPage interface to unload the JSP from memory.

--

--