1,需要修改
图片" src="http://b99.photo.store.qq.com/psb?/10c0ddec-acfa-423e-bfa8-a420ed0f2099/EaL4MgG.Meor4o1FJCAqD.QMaPGoorH2DccdWkKxYpw!/b/YY*4Dzt6LQAAYsTUCTt6LgAA">
中的context.xml文件:
添加:
工具类:ConnUtil
- packagecom.hw.util;
- importjava.sql.Connection;
- importjava.sql.DriverManager;
- importjava.sql.sqlException;
- importjavax.naming.Context;
- importjavax.naming.InitialContext;
- importjavax.naming.NamingException;
- importjavax.sql.DataSource;
- publicclassConnUtil
- {
- publicstaticConnectiongetConn()
- {
- Connectionconn=null;
- try
- {
- Class.forName("org.postgresql.Driver");
- Stringurl="jdbc:postgresql://192.168.2.150:5432/postgres";
- try
- {
- conn=DriverManager.getConnection(url,"postgres","postgres");
- }
- catch(sqlExceptione)
- {
- e.printStackTrace();
- }
- }
- catch(ClassNotFoundExceptione)
- {
- e.printStackTrace();
- }
- returnconn;
- }
- publicstaticConnectiongetJNDIConn(){
- Contextctx=null;
- try
- {
- ctx=newInitialContext();
- }
- catch(NamingExceptione1)
- {
- e1.printStackTrace();
- }
- Connectionconn=null;
- DataSourceds=null;;
- try
- {
- ds=(DataSource)ctx.lookup("java:comp/env/jdbc/postg");
- }
- catch(NamingExceptione)
- {
- e.printStackTrace();
- }
- try
- {
- conn=ds.getConnection();
- }
- catch(sqlExceptione)
- {
- e.printStackTrace();
- }
- returnconn;
- }
- }
servlet:
- packagecom.hw.servlet;
- importjava.io.IOException;
- importjava.io.PrintWriter;
- importjava.sql.Connection;
- importjava.sql.ResultSet;
- importjava.sql.sqlException;
- importjava.sql.Statement;
- importjavax.servlet.ServletException;
- importjavax.servlet.http.HttpServlet;
- importjavax.servlet.http.HttpServletRequest;
- importjavax.servlet.http.HttpServletResponse;
- importcom.hw.util.ConnUtil;
- /**
- *ServletimplementationclassPostgreServlet
- */
- publicclassPostgreServletextendsHttpServlet{
- privatestaticfinallongserialVersionUID=1L;
- /**
- *@seeHttpServlet#HttpServlet()
- */
- publicPostgreServlet(){
- super();
- }
- /**
- *@seeHttpServlet#doGet(HttpServletRequestrequest,HttpServletResponseresponse)
- */
- protectedvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{
- Connectionconn=ConnUtil.getJNDIConn();
- Stringsql="select*fromstudent";
- Statementstmt=null;
- ResultSetrs=null;
- PrintWriterout=response.getWriter();
- try
- {
- stmt=conn.createStatement();
- rs=stmt.executeQuery(sql);
- while(rs.next()){
- out.println(rs.getInt(1));
- }
- }
- catch(sqlExceptione)
- {
- e.printStackTrace();
- }
- }
- /**
- *@seeHttpServlet#doPost(HttpServletRequestrequest,HttpServletResponseresponse)
- */
- protectedvoiddoPost(HttpServletRequestrequest,IOException{
- doGet(request,response);
- }
- }
项目结构如下:
原文链接:https://www.f2er.com/postgresql/196679.html