KedarnathSir Ответов: 0

Как я на самом деле получаю контекстный объект после установки всего для DBCP (пула соединений с базой данных) в tomcat


Я получил соединение через Tomcat с базой данных MySQL непосредственно при написании кода из файла. jsp. Но когда я попытался сделать свою веб-страницу через DPCP, я не получил контекстный объект в своей программе сервлета.

Пожалуйста, проверьте мой код сервлета:

package servlet ;  


import java.io.IOException ;
import org.apache.catalina.core.Context ;
import org.apache.catalina.core.InitialContext ;
import java.io.PrintWriter ;
import javax.sql.DataSource ;
import java.sql.Connection ;
import java.sql.PreparedStatement ;
import java.sql.ResultSet ;
import javax.servlet.ServletConfig ;
import java.sql.SQLException ;
import javax.servlet.ServletException ;
import javax.servlet.http.HttpServlet ;
import javax.servlet.http.HttpServletRequest ;
import javax.servlet.http.HttpServletResponse ;
import javax.servlet.RequestDispatcher ;

public class FriendInfoServlet extends HttpServlet {
	private static final long SerialVersionUID = 1L ;
	
	DataSource dataSource = null ;
	
	public void init (ServletConfig config) {
		
		// init method has been called and servlet is initialized.
		try {
			/**
			  * Using the JNDI lookup get the DataSource.
			  */
			  Context initContext = new InitialContext () ;
			  Context envContext = (Context) initialContext.lookup ("java:comp/env") ;
			  dataSource = (DataSource) envContext.lookup ("jdbc/TestDB") ;
		}catch (Exception ex) {
			ex.printStackTrace() ;
		}	
	}
	
	public void doGet (HttpServletRequest request, HttpServletResponse response)
				throws ServletException, IOException {
		// doGet method has been called.
		response.setContentType ("text/html,content=\"UTF-8\"") ;
		
		PrintWriter out = response.getWriter () ;
		String title = "Our Friends' Information from MySQL Database" ;
		out.println ("<html><body bgcolor=\"#f0f0f0\">") ;
		out.println ("<h1 align=\"center\">" + title + "</h1>\n") ;
		
		showFriendInfo (out) ;
		
		out.println ("</body></html>") ;
	}
	
	
	public void destroy () {
		
	}
	
	
	private void showFriendInfo (PrintWriter out) {
		Connection conn = null ;
		
		PreparedStatement ps = null ;
		
		try {
			String sql = "SELECT * FROM friends limit ?" ;
			
			/**
			  * Get Connection from the DataSource.
			  */
			conn = dataSource.getConnection () ;
			
			/**
			  * Execute the Query.
			  */
			PreparedStatement ps = conn.PrepareStatement (sql) ;
			ps.setInt (1, 2) ;
			
			ResultSet rs = ps.executeQuery () ;
			
			while (rs.next ()) {
				int id = rs.getInt (1) ;
				String fName = rs.getString (2) + " " + rs.getString (3) ;
				String fType = rs.getString (4) ;
				String fMob = rs.getString (5) ;
			
				// Display Values
				out.print ("ID : " + id + "<br>") ;
				out.print ("Name : " + fName + "<br>") ;
				out.print ("Type : " + fType + "<br>") ;
				out.println ("Mobile # " + fMob + "<br>") ;
			}
			
			rs.close () ;
		} catch (Exception ex) {
			ex.printStackTrace () ;
		}
		
		finally {
			/**
      		  *	Finally block is used to close resources.
			  */
			try {
				if (ps != null) {
					ps.close () ;
				}
			} catch (SQLException sqle) {
				sqle.printStackTrace () ;
			}
			
			try {
				if (conn != null) {
					conn.close () ;
				}
			} catch (SQLException sqle) {
				sqle.printStackTrace () ;
			}
		}
	}
}


Что я уже пробовал:

Я попробовал Tomcat DCP How-to Guide и последовал всему необходимому.
Например, я установил свой Context.xml в папке META-INF следующим образом:

<?xml version="1.0" encoding="UTF-8"?>
<Context path="/dbtest">

<Resource name="jdbc/TestDB" auth="Container" type="javax.sql.DataSource"
		maxActive="100" maxIdle="30" maxWait="10000"
		userName="root" password="password" driverClassName="com.mysql.jdbc.Driver"
		url="jdbc:mysql://localhost:3306/test" />
		
</Context>

I have updated my web.xml file in WEB-INF folder, as follows:

<?xml version="1.0" encoding="ISO-8859-1"?>
<!--
 Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                      http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
  version="3.0"
  metadata-complete="true">

  <display-name>Friends' Information Displayer</display-name>
  
  <description>
     This is a simple web application with a source code organization
	 based on the recomendations of the Application Developer's Guide.
  </description>
  
  <servlet>
	<servlet-name>friendInfoServlet</servlet-name>
	<servlet-class>FriendInfoServlet</servlet-class>
  </servlet>
  
  <servlet-mapping>
	<servlet-name>friendInfoServlet</servlet-name>
	<url-pattern>/friendInfo</url-pattern>
  </servlet-mapping>
  
  <resource-ref>
	<description>Database Connection</description>
	<res-ref-name>jdbc/TestDB</res-ref-name>
	<res-type>javax.sql.DataSource</res-type>
	<res-auth>Container</res-auth>
  </resource-ref>

</web-app>

0 Ответов