The first step
Locate the <GlobalNamingResources> tag in the <tomcat installation directory >\conf\server.xml folder and add a label <resource>, this tag is configured as follows:
<resource
Name= "JDBC/WEBDB"//Database name
Auth= "Container"
Type= "Javax.sql.DataSource" driverclassname= "Com.mysql.jdbc.Driver" url= "Jdbc:mysql://localhost:3306/webdb? Characterencoding=utf-8 "
Username= "Root"
password= "1234"
Maxactive= "200"
Maxidle= "50"
Maxwait= "/>"
Step Two
Create a Webdemo.xml file in the <tomcat installation directory >\conf\catalina\localhost (Webdemo is the same as the project name), and then enter the following in the Webdemo.xml file
<context path= "/webdemo" docbase= "Webdemo" debug= "0" >
<resource name= "jdbc/webdb" auth= "Container"
Type= "Javax.sql.DataSource"
Driverclassname= "Com.mysql.jdbc.Driver"
Url= "Jdbc:mysql://localhost:3306/webdb?characterencoding=utf-8"
Username= "Root"
password= "1234"
Maxactive= "200"
Maxidle= "50"
Maxwait= "/>"
</Context>
Step Three
Add a Mysql-connector-java-5.1.18-bin.jar rack package to the Lib folder in the Wen-inf folder
Fourth Step
Add the following code to the Web. XML in your project
<servlet>
<servlet-name>ViewDictionary</servlet-name>
<servlet-class>ViewDictionary</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ViewDictionary</servlet-name>
<url-pattern>/servlet/ViewDictionary</url-pattern>
</servlet-mapping>
Note: Viewdictionary is the class name of the servlet that needs to be run
Fifth Step
Test in the Viewdictionary class with the following code
public class Viewdictionary extends HttpServlet
{
public void doget (HttpServletRequest request, httpservletresponse response)
Throws Servletexception, IOException
{
Response.setcontenttype ("Text/html;charset=utf-8");
PrintWriter out = Response.getwriter ();
Try
{
Javax.naming.Context CTX = new Javax.naming.InitialContext ();
Obtaining DataSource objects based on WEBDB data sources
Javax.sql.DataSource ds = (javax.sql.DataSource) ctx
. Lookup ("Java:/comp/env/jdbc/webdb");
Connection conn = Ds.getconnection ();
Execute SQL statement
PreparedStatement PSTMT = conn
. preparestatement ("SELECT * from T_dictionary");
ResultSet rs = Pstmt.executequery ();
StringBuilder table = new StringBuilder ();
Table.append ("<table border= ' 1 ' >");
Table.append ("<tr><td> title </td><td> price </td></tr>");
while (Rs.next ())//Generate query Results
{
Table.append ("<tr><td>" + rs.getstring ("中文版") + "</td><td>");
Table.append (rs.getstring ("Chinese") + "</td></tr>");
}
Table.append ("</table>");
Out.println (Table.tostring ()); Output query Results
Pstmt.close (); Close the PreparedStatement object
}
catch (Exception e)
{
Out.println (E.getmessage ());
}
}
}
MyEclipse using Jndi to connect to MySQL database