3.實現註入
3.1構建applicationContext.xml
在src目錄下建立applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
</beans>
3.1構建註入開始點
在HttpServer.java裡加入
private BeanFactory beanFactory;
public HttpServer() {
ClassPathResource classPathResource = new ClassPathResource(
"applicationContext.xml");
beanFactory = new XmlBeanFactory(classPathResource);
}
public Object getBean(String beenName){
return beanFactory.getBean(beenName);
}
3.2註入HttpServerPipelineFactory
在applicationContext.xml裡加入
<bean id="httpServerPipelineFactory" class="org.jboss.netty.example.http.snoop.HttpServerPipelineFactory" scope="prototype">
</bean>
修改HttpServer.java的main函數
public static void main(String[] args) {
// Configure the server.
ServerBootstrap bootstrap = new ServerBootstrap(
new NioServerSocketChannelFactory(
Executors.newCachedThreadPool(),
Executors.newCachedThreadPool()));
HttpServer httpServer = new HttpServer();
/ 提取httpServerPipelineFactory
HttpServerPipelineFactory httpServerPipelineFactory=(HttpServerPipelineFactory)httpServer.getBean("httpServerPipelineFactory");
// Set up the event pipeline factory.
bootstrap.setPipelineFactory(httpServerPipelineFactory);
// Bind and start to accept incoming connections.
bootstrap.bind(new InetSocketAddress(8081));
}
3.3HttpServerPipelineFactory註入HttpRequestHandler
把applicationContext.xml裡beans內容改為
<bean id="httpServerPipelineFactory" class="org.jboss.netty.example.http.snoop.HttpServerPipelineFactory" scope="prototype">
<property name="httpRequestHandler" ref="httpRequestHandler" />
</bean>
<bean id="httpRequestHandler" class="org.jboss.netty.example.http.snoop.HttpRequestHandler" scope="prototype">
</bean>
修改HttpServerPipelineFactory.java的main函數
public class HttpServerPipelineFactory implements ChannelPipelineFactory {
private HttpRequestHandler httpRequestHandler;
public void setHttpRequestHandler(HttpRequestHandler httpRequestHandler) {
this.httpRequestHandler = httpRequestHandler;
}
public HttpRequestHandler getHttpRequestHandler() {
return httpRequestHandler;
}
public ChannelPipeline getPipeline() throws Exception {
// Create a default pipeline implementation.
ChannelPipeline pipeline = pipeline();
// Uncomment the following line if you want HTTPS
// SSLEngine engine =
// SecureChatSslContextFactory.getServerContext().createSSLEngine();
// engine.setUseClientMode(false);
// pipeline.addLast("ssl", new SslHandler(engine));
pipeline.addLast("decoder", new HttpRequestDecoder());
// Uncomment the following line if you don't want to handle HttpChunks.
// pipeline.addLast("aggregator", new HttpChunkAggregator(1048576));
pipeline.addLast("encoder", new HttpResponseEncoder());
// Remove the following line if you don't want automatic content
// compression.
pipeline.addLast("deflater", new HttpContentCompressor());
pipeline.addLast("handler", httpRequestHandler);
return pipeline;
}
}
3.3HttpRequestHandler註入mysql連接池
把applicationContext.xml裡beans內容改為
<?xml version="1.0" encoding="UTF-8"?>
<!–
– Application context definition for JPetStore's business layer.
– Contains bean references to the transaction manager and to the DAOs in
– dataAccessContext-local/jta.xml (see web.xml's "contextConfigLocation").
–>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<!– =================================== 配置Spring數據源 ========================================= –>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://192.168.13.105:3306/gslb?useUnicode=true&characterEncoding=utf-8" />
<property name="username" value="gslb" />
<property name="password" value="testpass" />
<property name="maxIdle" value="10"/>
<property name="maxActive" value="100"/>
<property name="maxWait" value="10000"/>
<property name="validationQuery" value="select 1"/>
<property name="testOnBorrow" value="false"/>
<property name="testWhileIdle" value="true"/>
<property name="timeBetweenEvictionRunsMillis" value="1200000"/>
<property name="minEvictableIdleTimeMillis" value="1800000"/>
<property name="numTestsPerEvictionRun" value="5"/>
<property name="defaultAutoCommit" value="true"/>
</bean>
<!–
BasicDataSource提供瞭close()方法關閉數據源,所以必須設定destroy-method=”close”屬性,
以便Spring容器關閉時,數據源能夠正常關閉。除以上必須的數據源屬性外,
還有一些常用的屬性:
defaultAutoCommit:設置從數據源中返回的連接是否采用自動提交機制,默認值為 true;
defaultReadOnly:設置數據源是否僅能執行隻讀操作, 默認值為 false;
maxActive:最大連接數據庫連接數,設置為0時,表示沒有限制;
maxIdle:最大等待連接中的數量,設置為0時,表示沒有限制;
maxWait:最大等待秒數,單位為毫秒, 超過時間會報出錯誤信息;
validationQuery:用於驗證連接是否成功的查詢SQL語句,SQL語句必須至少要返回一行數據,
如你可以簡單地設置為:“select count(*) from user”;
removeAbandoned:是否自我中斷,默認是 false ;
removeAbandonedTimeout:幾秒後數據連接會自動斷開,在removeAbandoned為true,提供該值;
logAbandoned:是否記錄中斷事件, 默認為 false;
–>
<bean id="databaseUtil" class="org.jboss.netty.example.http.snoop.DatabaseUtil">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="httpServerPipelineFactory" class="org.jboss.netty.example.http.snoop.HttpServerPipelineFactory" scope="prototype">
<property name="httpRequestHandler" ref="httpRequestHandler" />
</bean>
<bean id="httpRequestHandler" class="org.jboss.netty.example.http.snoop.HttpRequestHandler" scope="prototype">
<property name="databaseUtil" ref="databaseUtil" />
</bean>
</beans>
修改HttpRequestHandler.java
package org.jboss.netty.example.http.snoop;
import static org.jboss.netty.handler.codec.http.HttpHeaders.*;
import static org.jboss.netty.handler.codec.http.HttpHeaders.Names.*;
import static org.jboss.netty.handler.codec.http.HttpResponseStatus.*;
import static org.jboss.netty.handler.codec.http.HttpVersion.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.jboss.netty.handler.codec.http.Cookie;
import org.jboss.netty.handler.codec.http.CookieDecoder;
import org.jboss.netty.handler.codec.http.CookieEncoder;
import org.jboss.netty.handler.codec.http.DefaultHttpResponse;
import org.jboss.netty.handler.codec.http.HttpChunk;
import org.jboss.netty.handler.codec.http.HttpChunkTrailer;
import org.jboss.netty.handler.codec.http.HttpRequest;
import org.jboss.netty.handler.codec.http.HttpResponse;
import org.jboss.netty.handler.codec.http.HttpResponseStatus;
import org.jboss.netty.handler.codec.http.QueryStringDecoder;
import org.jboss.netty.util.CharsetUtil;
/**
* @author <a href="http://www.jboss.org/netty/">The Netty Project</a>
* @author Andy Taylor (andy.taylor@jboss.org)
* @author <a href="http://gleamynode.net/">Trustin Lee</a>
*
* @version $Rev: 2368 $, $Date: 2010-10-18 17:19:03 +0900 (Mon, 18 Oct 2010) $
*/
public class HttpRequestHandler extends SimpleChannelUpstreamHandler {
private DatabaseUtil databaseUtil;
private HttpRequest request;
private boolean readingChunks;
/** Buffer that stores the response content */
private final StringBuilder buf = new StringBuilder();
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
System.out.println("messageReceived");
HttpRequest request = this.request = (HttpRequest) e.getMessage();
buf.setLength(0);
QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.getUri());
Map<String, List<String>> params = queryStringDecoder.getParameters();
if (!params.isEmpty()) {
HttpResponseStatus httpResponseStatus=HttpResponseStatus.OK;
if(params.containsKey("username")){
if(params.containsKey("password")){
List<String> values=params.get("username");
String username="";
if(values.size()>0){
username=values.get(0);
}
values=params.get("password");
String password="";
if(values.size()>0){
password=values.get(0);
}
try{
Connection conn=databaseUtil.getConnection();
if(conn!=null){
//查詢用戶名和密碼是否匹配
PreparedStatement ps=databaseUtil.getPrepStatement(conn,"select count(*) from user where name=? and password=?");
ps.setString(1, username);
ps.setString(2, password);
ResultSet rs=ps.executeQuery();
if(rs.next()){
if(rs.getInt(1)>0){
buf.append("FOUND");
}else{
buf.append("FOUND");
}
}else{
buf.append("QUERY ERROR");
}
databaseUtil.closeResultSet(rs);
databaseUtil.closePrepStatement(ps);
databaseUtil.closeConnection(conn);
}else{
buf.append("connot connect mysql");
}
}catch(Exception e1){
e1.printStackTrace();
buf.append("QUERY ERROR");
}
}else{
buf.append("miss password");
}
}else{
buf.append("miss username");
}
writeResponse(e,httpResponseStatus,buf);
}else{
buf.append("miss username and password");
writeResponse(e,OK,buf);
}
}
private void writeResponse(MessageEvent e,HttpResponseStatus httpResponseStatus,StringBuilder buf) {
// Decide whether to close the connection or not.
boolean keepAlive = isKeepAlive(request);
// Build the response object.
HttpResponse response = new DefaultHttpResponse(HTTP_1_1, httpResponseStatus);
response.setContent(ChannelBuffers.copiedBuffer(buf.toString(), CharsetUtil.UTF_8));
response.setHeader(CONTENT_TYPE, "text/plain; charset=UTF-8");
// Write the response.
ChannelFuture future = e.getChannel().write(response);
// Close the non-keep-alive connection after the write operation is done.
future.addListener(ChannelFutureListener.CLOSE);
}
private void send100Continue(MessageEvent e) {
HttpResponse response = new DefaultHttpResponse(HTTP_1_1, CONTINUE);
e.getChannel().write(response);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
throws Exception {
e.getCause().printStackTrace();
e.getChannel().close();
}
public void setDatabaseUtil(DatabaseUtil databaseUtil) {
this.databaseUtil = databaseUtil;
}
public DatabaseUtil getDatabaseUtil() {
return databaseUtil;
}
}
4.測試
訪問
http://127.0.0.1:8081/sdf?username=test1&password=1bbd886460827015e5d605ed44252221獲得FOUND即可
項目源代碼見:http://down.51cto.com/data/227126
本文出自 “一方有” 博客