http://blog.csdn.net/hgd250/article/details/2775833
http://blog.csdn.net/zzp_403184692/article/details/7854461
http://www.cnblogs.com/wang-meng/p/5463020.html
问题:
- 系统的dbcp创建过程
- dbcp的配置文档创建为xml时,如何使用
- properties创建使用
4.其他技术
ps:还在探索中。。。。。。
java中 synchronized 的使用,确保异步执行某一段代码
http://www.cnblogs.com/wayne173/p/4121516.html
创建数据源
package me.gacl.util;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.commons.dbcp2.BasicDataSourceFactory;
/**
* @ClassName: JdbcUtils_DBCP
* @Description: 数据库连接工具类
* @author: Jony
* @date: 2014-10-4 下午6:04:36
*
*/
public class JdbcUtils_DBCP {
/**
* 在java中,编写数据库连接池需实现java.sql.DataSource接口,每一种数据库连接池都是DataSource接口的实现
* DBCP连接池就是java.sql.DataSource接口的一个具体实现
*/
private static DataSource ds = null;
//在静态代码块中创建数据库连接池
static{
try{
//加载dbcpconfig.properties配置文件
InputStream in = JdbcUtils_DBCP.class.getClassLoader().getResourceAsStream("dbcpconfig.properties");
Properties prop = new Properties();
prop.load(in);
//创建数据源
ds = BasicDataSourceFactory.createDataSource(prop);
}catch (Exception e) {
throw new ExceptionInInitializerError(e);
}
}
/**
* @Method: getConnection
* @Description: 从数据源中获取数据库连接
* @Anthor:孤傲苍狼
* @return Connection
* @throws SQLException
*/
public static Connection getConnection() throws SQLException{
//从数据源中获取数据库连接
return ds.getConnection();
}
/**
* @Method: release
* @Description: 释放资源,
* 释放的资源包括Connection数据库连接对象,负责执行SQL命令的Statement对象,存储查询结果的ResultSet对象
* @Anthor:孤傲苍狼
*
* @param conn
* @param st
* @param rs
*/
public static void release(Connection conn,Statement st,ResultSet rs){
if(rs!=null){
try{
//关闭存储查询结果的ResultSet对象
rs.close();
}catch (Exception e) {
e.printStackTrace();
}
rs = null;
}
if(st!=null){
try{
//关闭负责执行SQL命令的Statement对象
st.close();
}catch (Exception e) {
e.printStackTrace();
}
}
if(conn!=null){
try{
//将Connection连接对象还给数据库连接池
conn.close();
}catch (Exception e) {
e.printStackTrace();
}
}
}
}
创建连接的类
package me.gacl.util;
//database
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
//Class
import me.gacl.domain.ClientInfo;
import me.gacl.domain.User;
import me.gacl.domain.RcuInfo;
//data sourcce
import me.gacl.util.JdbcUtils_DBCP;
public class RegisterUtil {
//注册完后,获取相关信息,用于返回客户端
public Integer roomIdInteger;
public RcuInfo rcuInfo;
//记录注册过程中的错误信息,内容不能有特殊字符
public String errorInfo;
public boolean register(User user, ClientInfo clientInfo) {
if (!user.isThePasswordCorrect("123456")) {
System.out.println("User password error !");
errorInfo = "User password error!";
return false;
}
if (!userInfoCheck(user)) {
System.out.println("userInfoCheck false !");
return false;
}
if (!addClientInfoToDatabase(user,clientInfo)) {
System.out.println("addClientInfoToDatabase false !");
return false;
}
return true;
}
private boolean userInfoCheck(User user) {
//记录状态
boolean isSuccess = false;
//System.out.println("userInfoCheck");
Connection con = null;
Statement sm = null;
ResultSet rs = null;
try{
//获取数据库连接
con = JdbcUtils_DBCP.getConnection();
sm = con.createStatement();
// 查询操作
String sqlSelect = "select * from room where RoomNum = "+user.getName()+"";
rs = sm.executeQuery(sqlSelect);
if(rs.next()){
roomIdInteger = rs.getInt("RID");
//rcuInfo.setIpString(rs.getString("zIP"));
//rcuInfo.setPortInteger(rs.getInt("zPort"));
int port = rs.getInt("zPort");
String ip = rs.getString("zIP");
rcuInfo = new RcuInfo(ip, port);
isSuccess = true;
//System.out.printf("zPort = %d,zIP = %s", port, ip);
}else {
errorInfo = "Room number doesn't exist !";
//return false;
}
}catch (Exception e) {
errorInfo = "Database error !";
e.printStackTrace();
}finally{
//释放资源
JdbcUtils_DBCP.release(con, sm, rs);
}
return isSuccess;
}
private boolean addClientInfoToDatabase(User user, ClientInfo clientInfo){
//记录状态
boolean isSuccess = false;
//System.out.println("addClientInfoToDatabase");
Connection conn = null;
Statement sm = null;
ResultSet rs = null;
try{
//获取数据库连接
conn = JdbcUtils_DBCP.getConnection();
sm = conn.createStatement();
String sqlUpdate = "update room set padIP='"+clientInfo.getIpString()+"',padPort='"+clientInfo.getPortInt()+"' where RoomNum = '"+user.getName()+"'";
int tag = sm.executeUpdate(sqlUpdate);
//System.out.printf("tag = %d",tag);
if (tag == 1) {
isSuccess = true;
}else {
isSuccess = false;
}
//tag=0不存在错误
}catch (Exception e) {
errorInfo = "Database error !";
e.printStackTrace();
}finally{
//释放资源
JdbcUtils_DBCP.release(conn, sm, rs);
}
return isSuccess;
}
}
附dbcpconfig.properties配置文件
src->New->file->file name:dbcpconfig.properties
#连接设置
driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
url=jdbc:sqlserver://localhost:1433;databaseName=IRCSData
username=sa
password=123
#
initialSize=10
#最大连接数量
maxActive=50
#
maxIdle=20
#
minIdle=5
#
maxWait=60000
#JDBC驱动建立连接时附带的连接属性属性的格式必须为这样:[属性名=property;]
#注意:"user" 与 "password" 两个属性会被明确地传递,因此这里不需要包含他们。
connectionProperties=useUnicode=true;characterEncoding=UTF8
#指定由连接池所创建的连接的自动提交(auto-commit)状态。
defaultAutoCommit=true
#driver default 指定由连接池所创建的连接的只读(read-only)状态。
#如果没有设置该值,则“setReadOnly”方法将不被调用。(某些驱动并不支持只读模式,如:Informix)
defaultReadOnly=
#driver default 指定由连接池所创建的连接的事务级别(TransactionIsolation)。
#可用值为下列之一:(详情可见javadoc。)NONE,READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE
defaultTransactionIsolation=READ_UNCOMMITTED
连接类创建对象,使用
package me.gacl.web.controller;
//database testting
import me.gacl.domain.ClientInfo;
import me.gacl.domain.User;
//import me.gacl.test.DataSourceTest;
//Register util
//import me.gacl.domain.ClientInfo;
//import me.gacl.domain.User;
//import me.gacl.domain.RcuInfo;
//import me.gacl.util.JdbcUtils_DBCP;
import me.gacl.util.RegisterUtil;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//import javax.servlet.jsp.tagext.TryCatchFinally;
public class RegisterServlet extends HttpServlet {
/**
* Constructor of the object.
*/
public RegisterServlet() {
super();
}
/**
* Destruction of the servlet.
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet.
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
boolean isSuccess = false;
//database testting
//DataSourceTest.dbcpDataSourceTest();
//get client data
String userId = request.getParameter("userId");
String userPwd = request.getParameter("userPwd");
String clientIp = request.getParameter("localIp");
String clientPort = request.getParameter("localPort");
//判断请求参数是否完整
if (userId == null|| userPwd == null||clientIp == null||clientPort == null) {
requestParamenterError(response);
System.out.println("Request paramenter error!");
return;
}
//注册功能
RegisterUtil registerUtil = new RegisterUtil();
User user = new User(userId, userPwd);
ClientInfo clientInfo = new ClientInfo(clientIp, Integer.parseInt(clientPort));
if (registerUtil.register(user, clientInfo)){
isSuccess = true;
System.out.printf("\nRegister return:RID = %d\t zIp = %s\tzPort = %d"
, registerUtil.roomIdInteger
, registerUtil.rcuInfo.getIpString()
, registerUtil.rcuInfo.getPortInt());
}else {
System.out.printf("\nRegister error !"
+ "\nError Info:"
+ registerUtil.errorInfo);
}
//return client
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
PrintWriter out = null;
String jsonString = "{\"isSuccess\":"+isSuccess;
if (isSuccess) {
jsonString += ", \"roomId\":"+registerUtil.roomIdInteger
+ ", \"rcuInfo\":{\"rcuIp\":\""+registerUtil.rcuInfo.getIpString()+"\", \"rcuPort\":"+registerUtil.rcuInfo.getPortInt()+"}"
+ "}";
}else{
jsonString += ",\"errorInfo\":\""+registerUtil.errorInfo+"\""
+"}";
}
try {
out = response.getWriter();
out.print(jsonString);
} catch (Exception e) {
e.printStackTrace();
} finally{
if(out != null){
out.close();
}
}
}
public void requestParamenterError(HttpServletResponse response) {
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
PrintWriter out = null;
String jsonString = "{\"isSuccess\":false, \"errorInfo\":\"Request paramenter error!\"}";
try {
out = response.getWriter();
out.print(jsonString);
} catch (Exception e) {
e.printStackTrace();
} finally{
if(out != null){
out.close();
}
}
}
/**
* The doPost method of the servlet.
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
/**
* Initialization of the servlet.
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}