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
問(wèn)題:
- 系統(tǒng)的dbcp創(chuàng)建過(guò)程
- dbcp的配置文檔創(chuàng)建為xml時(shí),如何使用
- properties創(chuàng)建使用
4.其他技術(shù)
ps:還在探索中展辞。胚膊。玫鸟。。稳其。疼电。
java中 synchronized 的使用分衫,確保異步執(zhí)行某一段代碼
http://www.cnblogs.com/wayne173/p/4121516.html
創(chuàng)建數(shù)據(jù)源
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: 數(shù)據(jù)庫(kù)連接工具類(lèi)
* @author: Jony
* @date: 2014-10-4 下午6:04:36
*
*/
public class JdbcUtils_DBCP {
/**
* 在java中模聋,編寫(xiě)數(shù)據(jù)庫(kù)連接池需實(shí)現(xiàn)java.sql.DataSource接口肩民,每一種數(shù)據(jù)庫(kù)連接池都是DataSource接口的實(shí)現(xiàn)
* DBCP連接池就是java.sql.DataSource接口的一個(gè)具體實(shí)現(xiàn)
*/
private static DataSource ds = null;
//在靜態(tài)代碼塊中創(chuàng)建數(shù)據(jù)庫(kù)連接池
static{
try{
//加載dbcpconfig.properties配置文件
InputStream in = JdbcUtils_DBCP.class.getClassLoader().getResourceAsStream("dbcpconfig.properties");
Properties prop = new Properties();
prop.load(in);
//創(chuàng)建數(shù)據(jù)源
ds = BasicDataSourceFactory.createDataSource(prop);
}catch (Exception e) {
throw new ExceptionInInitializerError(e);
}
}
/**
* @Method: getConnection
* @Description: 從數(shù)據(jù)源中獲取數(shù)據(jù)庫(kù)連接
* @Anthor:孤傲蒼狼
* @return Connection
* @throws SQLException
*/
public static Connection getConnection() throws SQLException{
//從數(shù)據(jù)源中獲取數(shù)據(jù)庫(kù)連接
return ds.getConnection();
}
/**
* @Method: release
* @Description: 釋放資源,
* 釋放的資源包括Connection數(shù)據(jù)庫(kù)連接對(duì)象链方,負(fù)責(zé)執(zhí)行SQL命令的Statement對(duì)象持痰,存儲(chǔ)查詢(xún)結(jié)果的ResultSet對(duì)象
* @Anthor:孤傲蒼狼
*
* @param conn
* @param st
* @param rs
*/
public static void release(Connection conn,Statement st,ResultSet rs){
if(rs!=null){
try{
//關(guān)閉存儲(chǔ)查詢(xún)結(jié)果的ResultSet對(duì)象
rs.close();
}catch (Exception e) {
e.printStackTrace();
}
rs = null;
}
if(st!=null){
try{
//關(guān)閉負(fù)責(zé)執(zhí)行SQL命令的Statement對(duì)象
st.close();
}catch (Exception e) {
e.printStackTrace();
}
}
if(conn!=null){
try{
//將Connection連接對(duì)象還給數(shù)據(jù)庫(kù)連接池
conn.close();
}catch (Exception e) {
e.printStackTrace();
}
}
}
}
創(chuàng)建連接的類(lèi)
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 {
//注冊(cè)完后,獲取相關(guān)信息祟蚀,用于返回客戶端
public Integer roomIdInteger;
public RcuInfo rcuInfo;
//記錄注冊(cè)過(guò)程中的錯(cuò)誤信息,內(nèi)容不能有特殊字符
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) {
//記錄狀態(tài)
boolean isSuccess = false;
//System.out.println("userInfoCheck");
Connection con = null;
Statement sm = null;
ResultSet rs = null;
try{
//獲取數(shù)據(jù)庫(kù)連接
con = JdbcUtils_DBCP.getConnection();
sm = con.createStatement();
// 查詢(xún)操作
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){
//記錄狀態(tài)
boolean isSuccess = false;
//System.out.println("addClientInfoToDatabase");
Connection conn = null;
Statement sm = null;
ResultSet rs = null;
try{
//獲取數(shù)據(jù)庫(kù)連接
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不存在錯(cuò)誤
}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
#連接設(shè)置
driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
url=jdbc:sqlserver://localhost:1433;databaseName=IRCSData
username=sa
password=123
#<!-- 初始化連接 -->
initialSize=10
#最大連接數(shù)量
maxActive=50
#<!-- 最大空閑連接 -->
maxIdle=20
#<!-- 最小空閑連接 -->
minIdle=5
#<!-- 超時(shí)等待時(shí)間以毫秒為單位 6000毫秒/1000等于60秒 -->
maxWait=60000
#JDBC驅(qū)動(dòng)建立連接時(shí)附帶的連接屬性屬性的格式必須為這樣:[屬性名=property;]
#注意:"user" 與 "password" 兩個(gè)屬性會(huì)被明確地傳遞工窍,因此這里不需要包含他們。
connectionProperties=useUnicode=true;characterEncoding=UTF8
#指定由連接池所創(chuàng)建的連接的自動(dòng)提交(auto-commit)狀態(tài)前酿。
defaultAutoCommit=true
#driver default 指定由連接池所創(chuàng)建的連接的只讀(read-only)狀態(tài)患雏。
#如果沒(méi)有設(shè)置該值,則“setReadOnly”方法將不被調(diào)用罢维。(某些驅(qū)動(dòng)并不支持只讀模式淹仑,如:Informix)
defaultReadOnly=
#driver default 指定由連接池所創(chuàng)建的連接的事務(wù)級(jí)別(TransactionIsolation)。
#可用值為下列之一:(詳情可見(jiàn)javadoc肺孵。)NONE,READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE
defaultTransactionIsolation=READ_UNCOMMITTED
連接類(lèi)創(chuàng)建對(duì)象匀借,使用
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. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* 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");
//判斷請(qǐng)求參數(shù)是否完整
if (userId == null|| userPwd == null||clientIp == null||clientPort == null) {
requestParamenterError(response);
System.out.println("Request paramenter error!");
return;
}
//注冊(cè)功能
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. <br>
*
* 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. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}