Click here to Skip to main content
15,881,172 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I got the connection through Tomcat to MySQL Database directly writing code from a .jsp file. But when I tried to make my webpage through DPCP, I am not getting the Context Object in my Servlet program.

Please verify my Servlet Code:

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 () ;
			}
		}
	}
}


What I have tried:

I tried the Tomcat DPCP How-to Guide and followed all the needful.
For example, I have set my Context.xml in META-INF folder as follows:

<?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>
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900