Connection pooling:
http://localhost:8089/Employee/getEmployee
Create context.xml
Create employee class
package com.jsl.servlet.demo; public class Employee { private int empno; private String ename; private String job; private double sal; public int getEmpno() { return empno; } public void setEmpno(int empno) { this.empno = empno; } public String getEname() { return ename; } public void setEname(String ename) { this.ename = ename; } public String getJob() { return job; } public void setJob(String job) { this.job = job; } public double getSal() { return sal; } public void setSal(double sal) { this.sal = sal; } }
Creating a EmployeeServlet Class
package com.jsl.servlet.demo; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.sql.DataSource; @WebServlet("/getEmployee") public class EmployeeServlet extends HttpServlet { private static final long serialVersionUID = 1L; Connection con=null; Statement st=null; ResultSet rs=null; DataSource ds=null; Context cx=null; @Override public void init() throws ServletException { try { cx=new InitialContext(); Context envContext = (Context) cx.lookup("java:/comp/env"); ds = (DataSource) envContext.lookup("jdbc/employee"); } catch (NamingException e) { e.printStackTrace(); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out=response.getWriter(); response.setContentType("text/html"); out.print("Employee List "); out.print(""); Listlist=getEmployeeList(); out.print(""); out.print(""); for(Employee emp:list){ out.print(""); out.print(""); out.print(""); out.print(""); } out.print(" "); out.print(""); } private List"); out.print("
EmpNo Empname Job Sal "+emp.getEmpno()+" "+emp.getEname()+" "+emp.getJob()+" "+emp.getSal()+" getEmployeeList() { List emplist=new ArrayList (); try{ con=ds.getConnection(); st=con.createStatement(); rs=st.executeQuery("select empno,ename,job,sal from emp"); while(rs.next()){ Employee emp=new Employee(); emp.setEmpno(rs.getInt("empno")); emp.setEname(rs.getString("ename")); emp.setJob(rs.getString("job")); emp.setSal(rs.getDouble("sal")); emplist.add(emp); } }catch(Exception e){ e.printStackTrace(); } return emplist; } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
http://localhost:8089/Employee/getEmployee