mysql jdbc netty_netty里集成spring注入mysq连接池(二)

3.实现注入

3.1构建applicationContext.xml

在src目录下建立applicationContext.xml

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">

3.1构建注入开始点

在HttpServer.java里加入

privateBeanFactory beanFactory;

publicHttpServer() {

ClassPathResource classPathResource =newClassPathResource(

"applicationContext.xml");

beanFactory =newXmlBeanFactory(classPathResource);

}

publicObject getBean(String beenName){

returnbeanFactory.getBean(beenName);

}

3.2注入HttpServerPipelineFactory

在applicationContext.xml里加入

修改HttpServer.java的main函数

publicstaticvoidmain(String[] args) {

// Configure the server.

ServerBootstrap bootstrap =newServerBootstrap(

newNioServerSocketChannelFactory(

Executors.newCachedThreadPool(),

Executors.newCachedThreadPool()));

HttpServer httpServer =newHttpServer();

/       提取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(newInetSocketAddress(8081));

}

3.3HttpServerPipelineFactory注入HttpRequestHandler

把applicationContext.xml里beans内容改为

修改HttpServerPipelineFactory.java的main函数

publicclassHttpServerPipelineFactoryimplementsChannelPipelineFactory {

privateHttpRequestHandler httpRequestHandler;

publicvoidsetHttpRequestHandler(HttpRequestHandler httpRequestHandler) {

this.httpRequestHandler = httpRequestHandler;

}

publicHttpRequestHandler getHttpRequestHandler() {

returnhttpRequestHandler;

}

publicChannelPipeline getPipeline()throwsException {

// 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",newHttpRequestDecoder());

// Uncomment the following line if you don't want to handle HttpChunks.

// pipeline.addLast("aggregator", new HttpChunkAggregator(1048576));

pipeline.addLast("encoder",newHttpResponseEncoder());

// Remove the following line if you don't want automatic content

// compression.

pipeline.addLast("deflater",newHttpContentCompressor());

pipeline.addLast("handler", httpRequestHandler);

returnpipeline;

}

}

3.3HttpRequestHandler注入mysql连接池

把applicationContext.xml里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">

destroy-method="close">

修改HttpRequestHandler.java

packageorg.jboss.netty.example.http.snoop;

importstaticorg.jboss.netty.handler.codec.http.HttpHeaders.*;

importstaticorg.jboss.netty.handler.codec.http.HttpHeaders.Names.*;

importstaticorg.jboss.netty.handler.codec.http.HttpResponseStatus.*;

importstaticorg.jboss.netty.handler.codec.http.HttpVersion.*;

importjava.sql.Connection;

importjava.sql.PreparedStatement;

importjava.sql.ResultSet;

importjava.util.List;

importjava.util.Map;

importjava.util.Map.Entry;

importjava.util.Set;

importorg.jboss.netty.buffer.ChannelBuffer;

importorg.jboss.netty.buffer.ChannelBuffers;

importorg.jboss.netty.channel.ChannelFuture;

importorg.jboss.netty.channel.ChannelFutureListener;

importorg.jboss.netty.channel.ChannelHandlerContext;

importorg.jboss.netty.channel.ExceptionEvent;

importorg.jboss.netty.channel.MessageEvent;

importorg.jboss.netty.channel.SimpleChannelUpstreamHandler;

importorg.jboss.netty.handler.codec.http.Cookie;

importorg.jboss.netty.handler.codec.http.CookieDecoder;

importorg.jboss.netty.handler.codec.http.CookieEncoder;

importorg.jboss.netty.handler.codec.http.DefaultHttpResponse;

importorg.jboss.netty.handler.codec.http.HttpChunk;

importorg.jboss.netty.handler.codec.http.HttpChunkTrailer;

importorg.jboss.netty.handler.codec.http.HttpRequest;

importorg.jboss.netty.handler.codec.http.HttpResponse;

importorg.jboss.netty.handler.codec.http.HttpResponseStatus;

importorg.jboss.netty.handler.codec.http.QueryStringDecoder;

importorg.jboss.netty.util.CharsetUtil;

/**

* @author The Netty Project

* @author Andy Taylor (andy.taylor@jboss.org)

* @author Trustin Lee

*

* @version $Rev: 2368 $, $Date: 2010-10-18 17:19:03 +0900 (Mon, 18 Oct 2010) $

*/

publicclassHttpRequestHandlerextendsSimpleChannelUpstreamHandler {

privateDatabaseUtil databaseUtil;

privateHttpRequest request;

privatebooleanreadingChunks;

/** Buffer that stores the response content */

privatefinalStringBuilder buf =newStringBuilder();

@Override

publicvoidmessageReceived(ChannelHandlerContext ctx, MessageEvent e)throwsException {

System.out.println("messageReceived");

HttpRequest request =this.request = (HttpRequest) e.getMessage();

buf.setLength(0);

QueryStringDecoder queryStringDecoder =newQueryStringDecoder(request.getUri());

Map> params = queryStringDecoder.getParameters();

if(!params.isEmpty()) {

HttpResponseStatus httpResponseStatus=HttpResponseStatus.OK;

if(params.containsKey("username")){

if(params.containsKey("password")){

List 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);

}

}

privatevoidwriteResponse(MessageEvent e,HttpResponseStatus httpResponseStatus,StringBuilder buf) {

// Decide whether to close the connection or not.

booleankeepAlive = isKeepAlive(request);

// Build the response object.

HttpResponse response =newDefaultHttpResponse(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);

}

privatevoidsend100Continue(MessageEvent e) {

HttpResponse response =newDefaultHttpResponse(HTTP_1_1, CONTINUE);

e.getChannel().write(response);

}

@Override

publicvoidexceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)

throwsException {

e.getCause().printStackTrace();

e.getChannel().close();

}

publicvoidsetDatabaseUtil(DatabaseUtil databaseUtil) {

this.databaseUtil = databaseUtil;

}

publicDatabaseUtil getDatabaseUtil() {

returndatabaseUtil;

}

}

b631442ad41f1993f5b451b7cd768a22.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值