Servlet Vs JSP

Servlet Vs JSP

Table of Contents

Servlets and JSPs are parts of a Java web application that is running on a web server. Both technologies are used to create dynamic web applications. The dynamic web application content can be changed depends on a specific request that was sent to the webserver. This gives the main benefit in comparison with a static web application.

Let’s understand what are the differences between Servlet and JSP technologies, and what they have in common.

Difference between Servlet and JSP

Servlet is written with Java code, JSP  can consist of either HTML or XML, or as a combination of both is also possible. Servlet code is harder to write as it is HTML in java. On the contrary, JSP has a Java code inside HTML, that is easier to write and to maintain.

Servlet is a controller in the Model-View-Controller approach. JSP is the view because dedicated mostly for showing an output. In general, Servlets are a bit faster than JavaServer Pages. The first step in JSP lifecycle is the translation of JSP to java code(Servlet) and just after this, it is compiling.

You can create different types of servlets, HTTPServlet is just a partial case. This means that Servlets can accept all requests. You can create a servlet that supports any protocol. On the contrary, JavaServer Pages support only HTTP protocol requests.

Servlets are more flexible, we can override the service() method. For JSP we don’t have such possibility. For Servlets you need to enable session management explicitly because by default session management is not enabled. And, vise versa, in JavaServer Pages session management is automatically enabled.

Servlet class contains the implementation of business logic and presentation logic in just one source java file. In the case of JSP, all logic is mostly in JavaBeans (Java class that sends data to corresponding JSP), presentation(view) is in JSP.

If you need to do modification in Servlet, it will take time, because it includes recompiling the java class, reloading it on the server, and restarting the server. The modification of JSP takes less time. You just need to refresh the browser page.

JSP technology allows you to build a custom tag. This is one of the key advantages because with re-usable components we get a lot of flexibility. On another side, servlets are written in Java language. Therefore, it allows using all Object Oriented programming techniques. You can easily encapsulate some functionality in another class. With JSPs we can make of the Javabeans inside the web pages. This means that some operations can be also encapsulated in some helpers and utils.

Let’s compare the Servlets and JSP’s life cycle. The fist of all, a JSP life cycle is pretty similar to a servlet life cycle with an additional step that is required to compile a JavaServer Pages into a servlet. JSP Compilation is the first step. When a browser requests a JSP, the JSP engine checks whether the compilation of the page is needed. In case the page has never been compiled or it was modified since the last compilation, the JSP engine is going to compile the page.

The compilation process has three steps: parsing the JSP, conversion of the JSP into a servlet, and compilation of the servlet. So,  JSPs have one additional step, called compilation. Secondly, Servlet life cycle methods are init(), service() and destroy(). JSP  life cycle methods are jspInit(), _jspService() and jspDestroy().

JSP and Servlet example

First of all we need to setup development environment. A development environment is where you develop your JSP, test, and run them. You need to set up the Java Development Kit. You can download SDK from the Oracle Java site.  After, you need to add JAVA_HOME variable to the Environment Variables of your Windows operating system.

In the case of Unix OS(Solaris, Linux, etc.),  you need to add JAVA_HOME into the .cshrc file.

There is a number of available Web Servers that support JavaServer Pages and Servlets development. A lot of web servers are free, One of such web servers is the Apache Tomcat. It is open-source software. To set up it, you need to download it and set the CATALINA_HOME environment variable.

Let’s move to our two simple examples that show text in a browser. The fist one is built as Servlet:

package servlets;

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 MyServlet extends HttpServlet {
  
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter writer = response.getWriter();
        try {
            writer.println("<h2>Welcome to servlets</h2>");
        } finally {
            writer.close();  
        }
    }
}

To create the servlet we extended HttpServlet. Also, we have to add the web.xml file to the WEB-INF folder, the deployment descriptor. Here is its content:

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

The output will be:

Servlet Vs JSP

The second example will do the same, but will be built with JSP.  Let’s create test.jsp file in folder WEB-INF\view. Here is its content:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>JSP</title>
</head>
<body>
<h2>Welcome to JSPs</h2>
</body>
</html>

The web.xml will be also different, because we need to map some requests on our JSP page :

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                      http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
  version="4.0">
   
 <servlet>
   <servlet-name>MyJSP</servlet-name>
   <jsp-file>/view/test.jsp</jsp-file>
</servlet>
<servlet-mapping>
  <servlet-name>MyJSP</servlet-name>
  <url-pattern>/myjsp</url-pattern>
</servlet-mapping>
</web-app>

After use of url /myjsp we will get our output:

Servlet Vs JSP

There is a possibility to get a text that created dynamically in the JavaBean.Servlet Vs JSP

Let’s try one more example.

We will use popular nowadays Spring Boot technology. In this kind of projects we don’t have web.xml. We will just add ViewResolver to our JSP, that point to folder with them.

package edu.controller;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

@Configuration
@EnableWebMvc
@ComponentScan
public class MvcConfiguration implements WebMvcConfigurer
{

    @Bean
    public ViewResolver internalResourceViewResolver() {
        InternalResourceViewResolver bean = new InternalResourceViewResolver();
        bean.setViewClass(JstlView.class);
        bean.setPrefix("/WEB-INF/view/");
        bean.setSuffix(".jsp");
        return bean;
    }
}

Also, you need to add maven dependencies:

<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<version>9.0.34</version>
</dependency>

Our test.jsp file in folder WEB-INF\view:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>JSP</title>
</head>
<body>
<h2>${message}</h2>
</body>
</html>

We are will use message from controller:

package edu.controller;

import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class JSPController {
 
    @RequestMapping("/myjsp")
    public String home(Map<String, Object> model) {
        model.put("message", "Welcome to JSPs");
        return "test";
    }
}

This application will have the same output as previous, but we sent values from java class that gives us a lot of advantages.

Servlet advantages

Servlets technology is a good way to generate easier to write and faster to run dynamic documents.

The first valuable thing to mention is the performance. Servlet is loaded after the first request and remain in memory till the destroy.

Secondly, is the simplicity. Servlet runs inside a controlled web server environment and you don’t need specific client software, a web browser is usually enough.  They provide easy portability across Web Servers.

One more advantage of servlets is session management. Since all web applications are stateless protocol, servlets overcome HTTP  stateless nature.   The servlets use its own API to maintain  session.

Servlets are built on Java Technology, which gives a lot of powerful features, such as Exception handling, garbage collection, network access, connectivity with Databases, integration with J2EE, etc.

Servlet Disadvantages

It is not easy to work with user interface designing in servlet and it slows down the application development.

When we are writing complex business logic in servlets, it makes the code difficult to understand.

You need to setup Java Runtime Environment on the server to run servlets. 

JSP Advantages 

The main advantage of JSP technology in comparison with Servlet technology is that it allows us to separate presentation logic(HTML) from business logic (Java code). Therefore, the code will be cleaner. work on the user interface will be quicker because the developer will see just the presentation code.

JSP technology allows tag-based programming, this means that extensive Java language knowledge is not required. JSP provides built-in JSP tags. Also, it allows us to develop custom tags or to use third-party tags, which makes the development of pages even easier. 

One more important advantage is that modification done in JSP is recognizing by webserver automatically. You don’t need to reload your web application.

JSP automatically takes care of exception handling, developers don’t need to explicitly handle this.

JSP Disadvantages

Anyway, even with a lot of cool features, JSP technology has room for improvement.

It is not easy to diagnose errors, because JSP pages are translated, and then compiled into Java servlets. All errors that appear in your pages will be rarely seen as errors arising from the coding of JSP pages. We will see them as Java servlet errors or HTML errors.

JSP pages require more disk space because the webserver has to store the resultant class files(generated from JSP pages) and the JSP pages themselves.

During the first access, JSP pages must be compiled on the server. This initial compilation causes a delay that is noticeable.

One Response

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Share this article