How to get data from database to servlet jdbc JSP

Here we will get data from the database to servlet JDBC and show data on the JSP page using Jakarta Server Pages and the JSTL library.

Technology used

  1. apache-tomcat-10.1.1
  2. JavaSE-17
  3. eclipse IDE for Enterprise Java and Web Developers

Steps to develop programs

  1. Create MySql Table and insert data
  2. Create A Dynamic Web Project
  3. Create package structure
  4. Create java files
  5. create jsp files

1 Create MySQL Table

Create a MySql table and insert a few data that will be retrieved from the database using our servlet program.

The script for creating the table is as below. Insert data as per need.

create table student(
  id bigint(20) unsigned NOT NULL AUTO_INCREMENT, 
  roll_no bigint(20), 
  name varchar(100), 
  course varchar(100), 
  session varchar(80), 
  semester varchar(80), 
  mobile_no varchar(30), 
  email_id varchar(100), 
  address varchar(200), 
  add_date timestamp DEFAULT CURRENT_TIMESTAMP, 
  primary key(id), 
  unique key(roll_no), 
  unique key(mobile_no), 
  unique key(email_id)
) ENGINE = InnoDB DEFAULT CHARSET = utf8;

Php MyAdmin Student Table data
Fig: Php MyAdmin Student Table data

Creating Java Dynamic Web Project

Open Eclipse IDE and follow the below steps

  1. Click on File->New-> Dynamic Web Project.
  2. Give project Name
  3. Select Target runtime (here apache-tomcat-10.1.1)
  4. then next again next then finish.

This will create a new project.

Creating packages and files

  1. Create packages com.ebhor.controller, com.ebhor.dao and com.ebhor.model inside src/main/java
  2. Create GetStudent.java servlet inside com.ebhor.controller
  3. Create ConnectionFactory and StudentDAO.java inside com.ebhor.dao
  4. Create Student.java inside com.ebhor.model
  5. Create a index.jsp and students.jsp inside webapp folder.

Project Explorer

External Jar

The following External jars are included in the apache tomcat lib folder

  1. mysql-connector-java-8.0.30
  2. jakarta.servlet.jsp.jstl-3.0.0
  3. jakarta.servlet.jsp.jstl-api-3.0.0

Servlet class to get data from DAO (GetStudents.java)

  1. Create a Dao object and access fetchAll(). This will return a List of students.
  2. Set the student list as an attribute in the request scope.
  3. Send the request and response to students.jsp using RequestDispatcher.
package com.ebhor.controller;
import java.io.IOException;
import java.util.List;
import com.ebhor.dao.StudentDAO;
import com.ebhor.model.Student;
import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
@WebServlet("/show-students")
public class GetStudents extends HttpServlet {
	private static final long serialVersionUID = 1L;
	StudentDAO dao = new StudentDAO();
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		List studentList = dao.fetchAll();
		request.setAttribute("students", studentList);
		RequestDispatcher requestDispatcher = request.getRequestDispatcher("/students.jsp");
		requestDispatcher.forward(request, response);
	}
}

Student Model class Student.java

Create a student model class to hold values of student objects and provide a getter, setter, constructor, and toString method.

package com.ebhor.model;

import java.io.Serializable;

public class Student implements Serializable {
	private static final long serialVersionUID = 7935940591376293207L;
	private long id;
	private long rollNo;
	private String name;
	private String course;
	private String session;
	private String semester;
	private String mailId;
	private String mobileNo;
	private String address;

	public Student() {

	}

	public Student(long id, long rollNo, String name, String course, String session, String semester, String mailId,
			String mobileNo, String address) {
		super();
		this.id = id;
		this.rollNo = rollNo;
		this.name = name;
		this.course = course;
		this.session = session;
		this.semester = semester;
		this.mailId = mailId;
		this.mobileNo = mobileNo;
		this.address = address;
	}

	@Override
	public String toString() {
		return "Student [id=" + id + ", rollNo=" + rollNo + ", name=" + name + ", course=" + course + ", session="
				+ session + ", semester=" + semester + ", mailId=" + mailId + ", mobileNo=" + mobileNo + ", address="
				+ address + "]";
	}

	public long getId() {
		return id;
	}

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

	public long getRollNo() {
		return rollNo;
	}

	public void setRollNo(long rollNo) {
		this.rollNo = rollNo;
	}

	public String getName() {
		return name;
	}

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

	public String getCourse() {
		return course;
	}

	public void setCourse(String course) {
		this.course = course;
	}

	public String getSession() {
		return session;
	}

	public void setSession(String session) {
		this.session = session;
	}

	public String getSemester() {
		return semester;
	}

	public void setSemester(String semester) {
		this.semester = semester;
	}

	public String getMailId() {
		return mailId;
	}

	public void setMailId(String mailId) {
		this.mailId = mailId;
	}

	public String getMobileNo() {
		return mobileNo;
	}

	public void setMobileNo(String mobileNo) {
		this.mobileNo = mobileNo;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

}

Connection with MySql and Getting Data from MySQL

ConnectionFactory.java

Instead of specifying a database connection to each JDBC call a class is created to return the Connection object.

package com.ebhor.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
 
public class ConnectionFactory {
 
 public static Connection getConnection() {
 Connection c = null;
 try {
 Class.forName("com.mysql.cj.jdbc.Driver");
 c = DriverManager.getConnection("jdbc:mysql://localhost:3306/ebhor","root", "");
 } catch (ClassNotFoundException e) {
 System.out.println("ClassNotFoundException " + e);
 } catch (SQLException e) {
 System.out.println("SQLException " + e);
 }
 return c;
 }
}

StudentDAO.java

To access student’s data from MySQL table JDBC Prepared statement is used.

Steps to read data from MySQL

  1. Get the connection object
  2. Prepare the PreparedStatement
  3. Execute the query and get ResultSet
  4. Iterate ResultSet object
  5. Prepare student objects and assign to student ArrayList.
  6. Close the connection
  7. Return students
package com.ebhor.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.ebhor.model.Student;
public class StudentDAO {
	Connection con = null;
	PreparedStatement ps = null;
	ResultSet rs = null;
	public List fetchAll() {
		List studentList = new ArrayList();
		con = ConnectionFactory.getConnection();
		try {
			String query = "select * from student order by id";
			ps = con.prepareStatement(query);
			rs = ps.executeQuery();
			while (rs.next()) {
				Student student = new Student();
				student.setId(rs.getLong("id"));
				student.setRollNo(rs.getLong("roll_no"));
				student.setName(rs.getString("name"));
				student.setCourse(rs.getString("course"));
				student.setSession(rs.getString("session"));
				student.setSemester(rs.getString("semester"));
				student.setMobileNo(rs.getString("mobile_no"));
				student.setMailId(rs.getString("email_id"));
				student.setAddress(rs.getString("address"));
			    studentList.add(student);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				con.close();
			} catch (SQLException ex) {
				ex.printStackTrace();
			}
		}
		return studentList;
	}
}

Index Page (index.jsp)

This page contains a link called Servlet.

<%@ page language="java" contentType="text/html; charset=utf-8"
	pageEncoding="utf-8"%>




Index Page


	

Student Details

Show Students

List of students (students.jsp)

After fetching data from the database servlet send a request response to this page.

This page iterates request scope object students using c:forEach. JSTL core tag library is used here.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="utf-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>



Student Details






	

List of Students

# Roll No Name Course Session Semester Mobile No Email Id Address
${loop.index+1} ${student.rollNo} ${student.name} ${student.course} ${student.session} ${student.semester} ${student.mobileNo} ${student.mailId} ${student.address}

Result

How To Get Data From Database To Servlet Jdbc
How To Get Data From Database To Servlet Jdbc
How To Get Data From Database To Servlet Jdbc
How To Get Data From Database To Servlet Jdbc
Q: jakarta.servlet.ServletException: java.lang.NoClassDefFoundError: jakarta/servlet/jsp/jstl/core/LoopTag

Along with jakarta.servlet.jsp.jstl-3.0.0 include jakarta.servlet.jsp.jstl-api-3.0.0

Q: org.apache.jasper.JasperException: The absolute uri: [http://java.sun.com/jsp/jstl/core] cannot be resolved in either web.xml or the jar files deployed with this application

Answer: Include jakarta.servlet.jsp.jstl-3.0.0 and supporting jar jakarta.servlet.jsp.jstl-api-3.0.0 to work it correctly.

Read More

Servlet url and class mapping using web.xml

Servlet Annotation WebServlet Example

ServletConfig to access initial parameter value

Servlet Maven Configuration Example

ServletContext getting parameter

Getting parameter values in Servlet getParameterNames

ServletContext getting multiple parameters

ServletConfig To Access Multiple Initial Parameter Value

getting all request parameters in servlet

Request dispatcher in Servlet User Login Example

Sending data to servlet using http get method