Open In App

Servlet With JDBC

Servlets are the Java programs that run on the Java-enabled web server or application server. They are used to handle the request obtained from the webserver, process the request, produce the response, then send a response back to the webserver.  Properties of Servlets are as follows:

Prerequisites:



What we are going to build in this article? 

In this example, we will be creating a simple “Student Database Management system” in which, we can insert, update, delete and view the student details.

Application

Step by Step Implementation

Step 1: Create Table in PostgreSQL



Table and columns

Step 2: Create a Dynamic web project in Eclipse

Project Structure

Step 3: Create required JSP’s to get the details from the student

Home.jsp

This is the welcome page of the project. On this page, we will be displaying the different types of operations such as Insert, Delete and Select data on the Student details.




<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Welcome Page</title>
</head>
<body>
  
    <h2 align="center">Welcome to Student database management system</h2>
    <br />
    <table align="center">
  
        <tr>
            <td>To insert your details into the Database:</td>
            <td><input type="button" value="Insert data"
                onclick="window.location.href='Insert.jsp'" /></td>
        </tr>
        <tr>
            <td>To delete your details from the Database:</td>
            <td><input type="button" value="Delete data"
                onclick="window.location.href='Delete.jsp'" /></td>
        </tr>
        <tr>
            <td>To view your details from the Database:</td>
            <td><input type="button" value="Select data"
                onclick="window.location.href='Select.jsp'" /></td>
        </tr>
    </table>
  
</body>
  
  
</html>

Based on the student selection, the respective JSP page will be displayed.

Insert.jsp

This page takes the required values from the student – Student Id, Student Name, Email Id, and Phone number and submits the page to Insert servlet to store the values in DB.




<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert Details</title>
</head>
<body>
  
    <h2>Fill in the details</h2>
  
    <form action="./InsertDetails" method="post">
        <table>
            <tr>
                <td>ID:</td>
                <td><input type="text" name="id" maxlength="6" size="7" /></td>
            </tr>
            <tr>
                <td>Name:</td>
                <td><input type="text" name="name" maxlength="30" size="25" /></td>
            </tr>
            <tr>
                <td>Email Id:</td>
                <td><input type="text" name="email" maxlength="40" size="35" /></td>
            </tr>
            <tr>
                <td>Phone Number:</td>
                <td><input type="text" name="phnum" maxlength="10" size="11" /></td>
            </tr>
            <tr />
        </table>
        <br /> <input type="submit" value="Insert Data" />
  
    </form>
    <br />
    <input type="button" value="Return to Home"
        onclick="window.location.href='Home.jsp'" />
  
  
</body>
  
</html>

Based on the action and method specified, it will map the respective servlet and go to the doPost method() in that servlet.

Delete.jsp

To delete the student information from DB, we need the ID of the student. This page takes the id from the student and submits the value to the Delete servlet.




<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Delete Details</title>
</head>
<body>
  
    <form action="./DeleteDetails" method="post">
        <table>
            <tr>
                <td>Enter ID:</td>
                <td><input type="text" name="id" maxlength="6" size="7" /></td>
            </tr>
  
        </table>
        <br /> <input type="submit" value="Delete Data" />
    </form>
    <br />
  
    <input type="button" value="Return to Home"
        onclick="window.location.href='Home.jsp'" />
  
</body>
  
</html>

Success.jsp

To display the success message after insert, update and delete operations.




<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Success Page</title>
</head>
<body>
    <form action="Home.jsp">
        <h3>
            <%=request.getParameter("msg")%>
            Successful
        </h3>
  
        <br /> <input type="submit" value="Return to Home page" />
  
    </form>
  
</body>
</html>

After successful insertion or deletion of the values, this page will display the success message to the UI. 

Select.jsp

To populate the student information from DB, we need the ID of the student. This page takes the id provided and submits it to the Select servlet to fetch the details.




<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Select Details</title>
</head>
<body>
  
    <form action="./SelectDetails" method="get">
        <table>
            <tr>
                <td>Enter ID:</td>
                <td><input type="text" name="id" maxlength="6" size="7" /></td>
            </tr>
  
        </table>
        <br /> <input type="submit" value="View Data" />
    </form>
    <br />
    <input type="button" value="Return to Home"
        onclick="window.location.href='Home.jsp'" />
  
</body>
  
</html>

Result.jsp

This page is to populate the student information in the UI. To display the result set of the student details based on the given id.




<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Student Details - Result</title>
</head>
<body>
  
    <h2>Details</h2>
  
    <form>
        <input type="hidden" name="stid"
            value="<%=request.getParameter("id")%>">
  
        <table>
            <tr>
                <td>ID:</td>
                <td><%=request.getParameter("id")%></td>
            </tr>
            <tr>
                <td>Name:</td>
                <td><%=request.getParameter("name")%></td>
            </tr>
            <tr>
                <td>Email Id:</td>
                <td><%=request.getParameter("email")%></td>
            </tr>
            <tr>
                <td>Phone Number:</td>
                <td><%=request.getParameter("phone")%></td>
            </tr>
            <tr />
        </table>
        <br />
    </form>
    <br />
    <input type="button" value="Update data" onclick="update()" />
    <br />
    <input type="button" value="Return to Home"
        onclick="window.location.href='Home.jsp'" />
  
</body>
  
<script language="javascript" type="text/javascript">
    function update() {
        var sid = document.forms[0].elements['stid'].value;
        window.location.href = "Update.jsp?id=" + sid;
    }
</script>
</html>

Update.jsp

Once the information is populated, if the student wants to update their details, this page takes the updated information from the student and submits it to the Update servlet.




<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Update Details</title>
</head>
<body>
  
    <h2>Fill in your details</h2>
  
    <form action="./UpdateDetails" method="post">
        <table>
            <tr>
                <td>ID:</td>
                <td><input type="text" name="id"
                    value="<%=request.getParameter("id")%>" readonly="readonly">
                </td>
            </tr>
            <tr>
                <td>Name:</td>
                <td><input type="text" name="name" maxlength="30" size="25" /></td>
            </tr>
            <tr>
                <td>Email Id:</td>
                <td><input type="text" name="email" maxlength="40" size="35" /></td>
            </tr>
            <tr>
                <td>Phone Number:</td>
                <td><input type="text" name="phnum" maxlength="10" size="11" /></td>
            </tr>
            <tr />
        </table>
        <br /> <input type="submit" value="Update Data" />
    </form>
    <br />
    <input type="button" value="Return to Home"
        onclick="window.location.href='Home.jsp'" />
  
</body>
</html>

We are making the ID value as read-only so that it won’t be changed and the information will be updated with respect to the ID value.

Step 4: Create DBUtil.java

To establish a JDBC connection with PostgreSQL, we need to specify the driver, URL, username, and password objects of the PostgreSQL. In order to reuse these objects in all the servlets to make a connection with the DB, we can provide these values in separate class like below.




public class DbUtil {
  
    public static String url = "jdbc:postgresql://localhost/postgres";
    public static String user = "root";
    public static String password = "root";
    public static String driver = "org.postgresql.Driver";
  
}

Instead of using a java class, we can specify these values in the properties file also.

Step 5: Create respective servlet classes

Servlet classes and JSP pages can be mapped through the web.xml(deployment descriptor) or by using annotations. In this example, we are using @WebServlet annotation to map the jsp pages to their respective servlets. To work with servlets, we need to extend the java class from HttpServlet.

InsertDetails.java

When the student enters the data through Insert.jsp and submits the page to insert the details into DB, based on the URL “/InsertDetails” in JSP page, InsertDetails.java servlet class will be mapped and executed.




import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
  
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
  
@WebServlet("/InsertDetails")
public class InsertDetails extends HttpServlet {
  
    private static final long serialVersionUID = 1L;
  
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
  
        // Jdbc Connection
        try {
            Class.forName(DbUtil.driver);
        } catch (ClassNotFoundException e) {
            System.out.println("Class not found " + e);
        }
        try {
            Connection conn = DriverManager.getConnection(DbUtil.url, DbUtil.user, DbUtil.password);
            System.out.println("connection successful");
              
              // Query/statement to insert the values
            PreparedStatement st = conn.prepareStatement("insert into studentdetails values(?, ?, ?, ?)");
  
            // set values into the query
            st.setInt(1, Integer.valueOf(request.getParameter("id")));
            st.setString(2, request.getParameter("name"));
            st.setString(3, request.getParameter("email"));
            st.setString(4, request.getParameter("phnum"));
  
            // Execute the query
            st.executeUpdate();
  
            st.close();
            conn.close();
  
            // Redirect the response to success page
            response.sendRedirect("Success.jsp?msg=Insert");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

DeleteDetails.java

Same as the insert operation delete servlet also will be mapped based on the URL specified. When a student enters the ID value to delete the student information, DeleteDetails.java servlet class will be mapped and executed.




import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
  
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
  
@WebServlet("/DeleteDetails")
public class DeleteDetails extends HttpServlet {
  
    private static final long serialVersionUID = 1L;
  
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
  
        try {
            Class.forName(DbUtil.driver);
        } catch (ClassNotFoundException e) {
            System.out.println("Class not found " + e);
        }
        try {
            Connection conn = DriverManager.getConnection(DbUtil.url, DbUtil.user, DbUtil.password);
            System.out.println("connection successful");
            PreparedStatement st = conn.prepareStatement("delete from studentdetails where stuid=?");
  
            st.setInt(1, Integer.valueOf(request.getParameter("id")));
  
            st.executeUpdate();
  
            st.close();
            conn.close();
  
            response.sendRedirect("Success.jsp?msg=Delete");
  
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

SelectDetails.java

To populate the student information based on the ID submitted.




import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
  
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
  
@WebServlet("/SelectDetails")
public class SelectDetails extends HttpServlet {
  
    private static final long serialVersionUID = 1L;
  
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
  
        try {
            Class.forName(DbUtil.driver);
        } catch (ClassNotFoundException e) {
            System.out.println("Class not found " + e);
        }
        try {
  
            int id = 0;
            String name = "", email = "", ph = "";
  
            Connection conn = DriverManager.getConnection(DbUtil.url, DbUtil.user, DbUtil.password);
            System.out.println("connection successful");
            PreparedStatement st = conn.prepareStatement("select * from studentdetails where stuid=?");
  
            st.setInt(1, Integer.valueOf(request.getParameter("id")));
  
            ResultSet rs = st.executeQuery();
  
            while (rs.next()) {
  
                id = rs.getInt(1);
                name = rs.getString(2);
                email = rs.getString(3);
                ph = rs.getString(4);
  
            }
  
            rs.close();
            st.close();
            conn.close();
  
            response.sendRedirect("Result.jsp?id=" + id + "&name=" + name + "&email=" + email + "&phone=" + ph);
  
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
  
}

UpdateDetails.java

If the student wants to update any information, then we need to get the respective ID and perform the operation.




import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
  
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
  
@WebServlet("/UpdateDetails")
public class UpdateDetails extends HttpServlet {
  
    private static final long serialVersionUID = 1L;
  
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
  
        try {
            Class.forName(DbUtil.driver);
        } catch (ClassNotFoundException e) {
            System.out.println("Class not found " + e);
        }
        try {
            Connection conn = DriverManager.getConnection(DbUtil.url, DbUtil.user, DbUtil.password);
            System.out.println("connection successful");
            PreparedStatement st = conn
                    .prepareStatement("update studentdetails set stuname=?, email=?, phonenum=? where stuid=?");
  
            st.setString(1, request.getParameter("name"));
            st.setString(2, request.getParameter("email"));
            st.setString(3, request.getParameter("phnum"));
            st.setInt(4, Integer.valueOf(request.getParameter("id")));
  
            st.executeUpdate();
  
            st.close();
            conn.close();
  
            response.sendRedirect("Success.jsp?msg=Update");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
  
}

Step 6: Run the Application

Now, run the application using Run As -> Run on Server. The application will be deployed on the Tomcat server. Run the URL, http://localhost:8081/ServletsPostgre/Home.jsp, in the browser to get the home page of the application.

Home.jsp

Insert.jsp

Successful message

Insertion

Select.jsp

Student_info

Update.jsp

Updated_details

Delete.jsp

Deletion_successful

After delete operation

In this way, we can perform all the insert, update, delete and select operations using Servlets with JDBC. 


Article Tags :