Tomcat6.0 JNDI数据源经典实例

mysql建表语句:

CREATE TABLE `tomcat` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(100) DEFAULT NULL,
  `password` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1





//DatabaseConnection.java

package com.abin.tomcat.data;

import java.sql.*;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class DatabaseConnection {
private static final String DSNAME = "java:comp/env/jdbc/mysql";

private Connection conn;

public DatabaseConnection() {
  Context ctx = null;
  try {
   ctx = new InitialContext();
  } catch (NamingException e) {
   e.printStackTrace();
  }
  DataSource ds = null;
  try {
   ds = (DataSource) ctx.lookup(DSNAME);
  } catch (NamingException e) {
   e.printStackTrace();
  }
  try {
   this.conn = ds.getConnection();
  } catch (SQLException e) {
   e.printStackTrace();
  }
}

public Connection getConnection() {
  return conn;
}

public void close() throws Exception {
  if (conn != null) {
   try {
    conn.close();
    conn = null;
   } catch (Exception e) {

    throw e;
   } finally {
    if (conn != null) {
     try {
      conn.close();
     } catch (Exception e) {
      e.printStackTrace();
     }
    }
   }
  }
}

}










//TomcatServlet.java

package com.abin.tomcat.data;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TomcatServlet extends HttpServlet {

public void init(ServletConfig config) throws ServletException {
  super.init();
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  String username = request.getParameter("username");
  String password = request.getParameter("password");
  Connection conn = null;
  PreparedStatement ps = null;
  String sql = "insert into tomcat (username,password) values (?,?)";
  try {
   conn = DBClassConnection.getConnection();
   ps = conn.prepareStatement(sql);
   ps.setString(1, username);
   ps.setString(2, password);
   ps.executeUpdate();
   request.getSession().setAttribute("message", "operate success");
   String target = "message.jsp";
   request.getRequestDispatcher(target).forward(request, response);

  } catch (Exception e) {
   // TODO: handle exception
   e.printStackTrace();
  }

}

public void destroy() {
  super.destroy();
}

}







//context.xml 放置于D:\SystemFile\MyeclipseWorkspace\TomSource\WebRoot\META-INF\这个目录下面

<?xml version="1.0" encoding="UTF-8"?>
<Context path="/TomSource"
    docBase="D:\SystemFile\MyeclipseWorkspace\TomSource\WebRoot"
    debug="5"
    reloadable="true"
    crossContext="true">
<Resource
      name="jdbc/mysql"
      type="javax.sql.DataSource"
      password=""
      driverClassName="com.mysql.jdbc.Driver"
      maxIdle="2"
      maxWait="50"
      username="root"
      url="jdbc:mysql://localhost:3306/abin"
      maxActive="4"/>

</Context>





//web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

<servlet>
  <servlet-name>TomcatServlet</servlet-name>
  <servlet-class>com.abin.tomcat.data.TomcatServlet</servlet-class>
</servlet>

<servlet-mapping>
  <servlet-name>TomcatServlet</servlet-name>
  <url-pattern>/TomcatServlet</url-pattern>
</servlet-mapping>

<resource-ref>
  <description>DB Connection</description>
  <res-ref-name>jdbc/mysql</res-ref-name>
  <res-type>javax.sql.DataSource</res-type>
  <res-auth>Container</res-auth>
</resource-ref>


  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>




//index.jsp放置于WebRoot目录下面:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
  <title>TOMCAT DATASOURCE</title>
</head>

<body>

<form action="TomcatServlet" method="post">
用户名:<br/>
  <input name="username" type="text" /><br/>
密码:<br/>
  <input name="password" type="password" /><br/>
  <input  type="submit"  value="提交" />
  <input  type="reset"  value="重置" />
</form>

</body>
</html>






//message.jsp放置于WebRoot目录下面:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
  <title>TOMCAT DATASOURCE</title>
</head>

<body>
  <%=session.getAttribute("message") %>

</body>
</html>






//JAR包这里只用到mysql-connector-java-5.1.15-bin.jar放置于lib里面就好了,直接发布到tomcat6就可以访问了。

你可能感兴趣的:(tomcat,servlet,jdbc)