Improving Servlet performance to fetch records from database

Improving Servlet performance to fetch records from the database

In this example, we are going to discuss how to Improving Servlet performance to fetch records from the database. Please read our previous article where we discussed How to Fetch Data from the Database using Servlet. Here we are storing the data of the table is a collection, and reusing this collection in our servlet. So, we do not need to directly hit the database again and again. By this, we are improving the performance.

First, we need to create the following table:
CREATE TABLE user   
(    
     userid INT,   
     username VARCHAR2(45),   
     userpass VARCHAR2(50),   
     useremail VARCHAR2(100),   
     usercountry VARCHAR2(45),   
     contact INT,   
     PRIMARY KEY (USERID)   
) 

Now insert the following records into the table.

Improving Servlet performance to fetch records from the database

In this example, we have created 6 resources as follows:

  1. index.html
  2. User.java
  3. MyListener.java
  4. MyServlet1.java
  5. Myservlet2.java
  6. web.xml

index.html file contains two links that send requests to the servlet. User.java is a simple bean class containing three properties with its getters and setters. This class represents the table of the database. MyListener.java is the listener class. When the project will be deployed, the contextInitialized method of ServletContextListener is invoked by default. Here, we are getting the records of the table and storing it in the User class object which is added in the ArrayList class object. At last, all the records of the table will be stored in the ArrayList class object (collection). Finally, we are storing the ArrayList object in the ServletContext object as an attribute so that we can get it in the servlet and use it. MyServlet1.java gets the information from the servlet context object and prints it. MyServlet2.java is the same as MyServlet1. This servlet gets the information from the servlet context object and prints it. web.xml is containing information about servlets and listeners.

index.html
<html>
<body>
 <a href="servlet1">first servlet</a>|  
 <a href="servlet2">second servlet</a>  	 
</body>
</html>
User.java
public class User 
{
 private int id;
 private String name, password;

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public String getPassword() {
  return password;
 }

 public void setPassword(String password) {
  this.password = password;
 }
}
MyListener.java
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.sql.*;
import java.util.ArrayList;

public class MyListener implements ServletContextListener {

 public void contextInitialized(ServletContextEvent e) {

  ArrayList list = new ArrayList();
  try {
   Class.forName("com.mysql.jdbc.Driver");
   Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/userdb", "root", "876745");
   PreparedStatement ps = con.prepareStatement("select * from user");
   ResultSet rs = ps.executeQuery();
   while (rs.next()) {
    User u = new User();
    u.setId(rs.getInt(1));
    u.setName(rs.getString(2));
    u.setPassword(rs.getString(3));
    list.add(u);
   }
   con.close();

  } catch (Exception ex) {
   System.out.print(ex);
  }

  // storing the ArrayList object in ServletContext
  ServletContext context = e.getServletContext();
  context.setAttribute("data", list);

 }

 public void contextDestroyed(ServletContextEvent arg0) {
  System.out.println("project undeployed...");
 }
}
MyServlet1.java
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyServlet1 extends HttpServlet {
 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

  response.setContentType("text/html");
  PrintWriter out = response.getWriter();

  long before = System.currentTimeMillis();

  ServletContext context = getServletContext();
  List list = (List) context.getAttribute("data");

  Iterator itr = list.iterator();
  while (itr.hasNext()) {
   User u = (User) itr.next();
   out.print("<br>" + u.getId() + " " + u.getName() + " " + u.getPassword());
  }

  long after = System.currentTimeMillis();
  out.print("<br>total time :" + (after - before));

  out.close();
 }
}
MyServlet2.java
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyServlet2 extends HttpServlet {
 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

  response.setContentType("text/html");
  PrintWriter out = response.getWriter();

  long before = System.currentTimeMillis();

  ServletContext context = getServletContext();
  List list = (List) context.getAttribute("data");

  Iterator itr = list.iterator();
  while (itr.hasNext()) {
   User u = (User) itr.next();
   out.print("<br>" + u.getId() + " " + u.getName() + " " + u.getPassword());
  }

  long after = System.currentTimeMillis();
  out.print("<br>total time :" + (after - before));

  out.close();
 }
}

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

 <listener>
  <listener-class>MyListener</listener-class>
 </listener>

 <servlet>
  <servlet-name>MyServlet1</servlet-name>
  <servlet-class>MyServlet1</servlet-class>
 </servlet>
 <servlet>
  <servlet-name>MyServlet2</servlet-name>
  <servlet-class>MyServlet2</servlet-class>
 </servlet>

 <servlet-mapping>
  <servlet-name>MyServlet1</servlet-name>
  <url-pattern>/servlet1</url-pattern>
 </servlet-mapping>
 <servlet-mapping>
  <servlet-name>MyServlet2</servlet-name>
  <url-pattern>/servlet2</url-pattern>
 </servlet-mapping>
</web-app>  
Output

Run your project to get the following output:

Improve Servlet performance

Click on the “first servlet” link and you will get the following output:

Improve Servlet performance to fetch records from the database

When you will click on the “second servlet” link, you will get the following output:

How to Improve Servlet performance to fetch records from the database

In the next article, I am going to discuss How to upload files to servers in servlet. Here, in this article, we develop an application to Improve Servlet performance to fetch records from the database and I hope you enjoy this How to Improve Servlet performance to fetch records from the database article.

Leave a Reply

Your email address will not be published.