Skip to content
Related Articles

Related Articles

Improving Servlet Performance to Fetch Records From Database

View Discussion
Improve Article
Save Article
Like Article
  • Last Updated : 05 Apr, 2022

Here we will be boosting the web application’s ability to retrieve records from the database. To provide this, we save the table’s data in a collection and reuse that collection in our servlet. As a result, we aren’t repeatedly querying the database. We are enhancing our performance as a result of this. In order to begin, we must first generate the following table:

Table:

CREATE TABLE gfguser  
(    
    userid INT,  
    username VARCHAR(50),  
    userpass VARCHAR(50),  
    useremail VARCHAR(100),  
    usercountry VARCHAR(50),  
    contact INT,  
    PRIMARY KEY (USERID)  
)

Now, inside the table, add the following records.

Implementation: In this case, we’ve generated the following six resources:

  1. index.html
  2. User.java
  3. MainListenerGfg.java
  4. Servlet1.java
  5. servlet2.java
  6. web.xml

Two links in the index.html file transmit requests to the servlet. User.java is a straightforward bean class with three attributes and their associated getters and setters. The database table is represented by this class. The listener class is MainListenerGfg.java. The contextInitialized method of ServletContextListener is called by default when the project is deployed. We are retrieving the table’s records and saving them in the User class object, which has been added to the ArrayList class object. Lastly, the ArrayList class object will be used to hold all of the table’s records (collection).

Finally, we save the ArrayList object as an attribute in the ServletContext object so that we can utilize it in the servlet. Servlet1.java retrieves and outputs information from the servlet context object. Servlet2.java is identical to Servlet1.java. The information from the servlet context object is printed by this servlet. Information regarding servlets and listeners may be found in web.xml.

A. index.html

Java




<html>
<body>
<h1> GeeksForGeeks</h1>
 <a href="servlet1">This is first servlet</a>|  //first link
 <a href="servlet2">This is second servlet</a>  //second link
</body>
</html>


B. User.java

Java




// Java Program to Illustrate User Class
 
// Class
public class User {
   
    // Declaring variables to
    // access data from database
    private int id;
    private String name, password;
 
    // Adding getters and setter for variables
 
    // Getters and Setters
    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;
    }
}


C. MainListenerGfg.java

Java




// Java Program to Illustrate MainListener Class
 
// Importing required classes
import java.sql.*;
import java.util.ArrayList;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
 
// Class
// implementing ServletContextListener interface
public class MainListenerGfg
    implements ServletContextListener {
 
    // Method 1
    public void contextInitialized(ServletContextEvent e)
    {
 
        // Creating an empty ArrayList
        ArrayList list = new ArrayList();
 
        // Try block to check for exceptions
        try {
 
            // Loading drivers by
            // connecting with database
            Class.forName("com.mysql.jdbc.Driver");
 
            Connection con = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/geeksforgeeks",
                "root", "root");
 
            PreparedStatement ps = con.prepareStatement(
                "select * from gfguser");
            ResultSet rs = ps.executeQuery();
 
            // Accessing all data until its empty
            // using next() method
            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);
            }
 
            // Closing the connections
            // using close() method
            con.close();
        }
 
        // Catch block to handle exceptions
        catch (Exception ex) {
 
            // Displaying the exceptions
            System.out.print(ex);
        }
 
        // Storing the ArrayList object in ServletContext
        ServletContext context = e.getServletContext();
        context.setAttribute("data", list);
    }
 
    // Method 2
    public void contextDestroyed(ServletContextEvent arg0)
    {
        // Print statement whenever this method is called
        System.out.println("project undeployed...");
    }
}


D.Servlet1.java

Java




// Java Program to Illustrate Servlet Class
 
// Importing required classes
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;
 
// Class
// Extending HttpServlet Class
public class Servlet1 extends HttpServlet {
 
    // Method
    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();
 
        // Condition holds true till there is single element
        // remaining in the List
        while (itr.hasNext()) {
            User u = (User)itr.next();
            out.print("<br>" + u.getId() + " " + u.getName()
                      + " " + u.getPassword());
        }
 
        // Closing the connections
        // using close() method
        out.close();
    }
}


E. Servlet2.java

Java




// Java Program to Illustrate Servlet Class
 
// Importing required classes
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;
 
// Class
// Extending HttpServlet class
public class Servlet2 extends HttpServlet {
 
    // Method
    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
        Iterator itr = list.iterator();
 
        // Condition holds true till
        // there is single element remaining
        while (itr.hasNext()) {
            User u = (User)itr.next();
            out.print("<br>" + u.getId() + " " + u.getName()
                      + " " + u.getPassword());
        }
 
        // Closing the connections
        // using close() method
        out.close();
    }
}


F. web.xml

XML




<web-app>
 <listener>
  <listener-class>MainListenerGfg</listener-class>
 </listener>
 
 <servlet>
  <servlet-name>Servlet1</servlet-name>
  <servlet-class>Servlet1</servlet-class>
 </servlet>
 <servlet>
  <servlet-name>Servlet2</servlet-name>
  <servlet-class>Servlet2</servlet-class>
 </servlet>
 
 <servlet-mapping>
  <servlet-name>Servlet1</servlet-name>
  <url-pattern>/servlet1</url-pattern>
 </servlet-mapping>
 <servlet-mapping>
  <servlet-name>Servlet2</servlet-name>
  <url-pattern>/servlet2</url-pattern>
 </servlet-mapping>
</web-app>


Output:

In order to receive the following output, run the index.html file:

We will get the following result if you click on the “This is first servlet” link:

The following output will appear when you click on the “This is second servlet” link:


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!