1,需要修改
中的context.xml文件:
添加:
- <Resource driverClassName="org.postgresql.Driver" maxActive="4" maxIdle="2" maxWait="50"
- auth="Container"
- name="jdbc/postg" password="root" type="javax.sql.DataSource"
- url="jdbc:postgresql://192.168.2.150:5432/postgres" username="postgres"/>
工具类:ConnUtil
- package com.hw.util;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.SQLException;
- import javax.naming.Context;
- import javax.naming.InitialContext;
- import javax.naming.NamingException;
- import javax.sql.DataSource;
- public class ConnUtil
- {
- public static Connection getConn()
- {
- Connection conn = null;
- try
- {
- Class.forName("org.postgresql.Driver");
- String url = "jdbc:postgresql://192.168.2.150:5432/postgres";
- try
- {
- conn = DriverManager.getConnection(url, "postgres", "postgres");
- }
- catch (SQLException e)
- {
- e.printStackTrace();
- }
- }
- catch (ClassNotFoundException e)
- {
- e.printStackTrace();
- }
- return conn;
- }
- public static Connection getJNDIConn(){
- Context ctx=null;
- try
- {
- ctx = new InitialContext();
- }
- catch (NamingException e1)
- {
- e1.printStackTrace();
- }
- Connection conn=null;
- DataSource ds=null;;
- try
- {
- ds = (DataSource)ctx.lookup("java:comp/env/jdbc/postg");
- }
- catch (NamingException e)
- {
- e.printStackTrace();
- }
- try
- {
- conn=ds.getConnection();
- }
- catch (SQLException e)
- {
- e.printStackTrace();
- }
- return conn;
- }
- }
servlet:
- package com.hw.servlet;
- import java.io.IOException;
- import java.io.PrintWriter;
- import java.sql.Connection;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.sql.Statement;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import com.hw.util.ConnUtil;
- /**
- * Servlet implementation class PostgreServlet
- */
- public class PostgreServlet extends HttpServlet {
- private static final long serialVersionUID = 1L;
- /**
- * @see HttpServlet#HttpServlet()
- */
- public PostgreServlet() {
- super();
- }
- /**
- * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
- */
- protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- Connection conn=ConnUtil.getJNDIConn();
- String sql="select * from student";
- Statement stmt=null;
- ResultSet rs=null;
- PrintWriter out=response.getWriter();
- try
- {
- stmt=conn.createStatement();
- rs=stmt.executeQuery(sql);
- while(rs.next()){
- out.println(rs.getInt(1));
- }
- }
- catch (SQLException e)
- {
- e.printStackTrace();
- }
- }
- /**
- * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
- */
- protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- doGet(request, response);
- }
- }
项目结构如下: