网络编程三--报文发送

网络编程三

一、网络交互之RPC

1.RPC

	RPC(Remote Procedure Call)—远程过程调用,它是一种通过网络从远程计算机程
序上请求服务,而不需要了解底层网络技术的协议,RPC允许程序调用另一个地址空间(通常是
共享网络的另一台机器上)的过程或函数,而不需要显式编码这个远程调用的细节
	
	简而言之:我们可以理解为是一种不同计算机之间的网络交互的协议

2.RPC的特点

	通过网络传输的
	
	跨终端、跨平台的
	
	基于请求-响应
	
	只调用过程,不需关注细节

3.RPC的基本原理

	在底层去看,RPC其实就是将流从一台计算机传输到另外一台计算机

4.常见的RPC的调用技术

	Thrift:thrift是一个软件框架,用来进行可扩展且跨语言的服务的开发。它结合了
功能强大的软件堆栈和代码生成引擎,以构建在 C++, Java, Python, PHP, Ruby, 
Erlang, Perl, Haskell, C#, Cocoa, JavaScript, Node.js, Smalltalk, 
and OCaml 这些编程语言间无缝结合的、高效的服务
	SpringCloud(Spring的,基于Socket的,SOA架构的分布式框架)

    Dubbo(x)(阿里巴巴的,基于Socket的,SOA架构的分布式框架)

    WebService(跨语言的,基于SOAP协议,走xml数据或json数据)

    Hessian(跨语言的,基于Binary-RPC协议,走二进制数据)

    HttpClient(通常用于RESTful风格的调用,跨语言,基于http和json)

    jdk原生(HttpURLConnection)

二、报文发送

1.报文

	定义:报文(message)是网络中交换与传输的数据单元,即站点一次性要发送的数据块。
报文包含了将要发送的完整的数据信息,其长短很不一致,长度不限且可变。
	
	简而言之,报文就是在各个系统之间进行请求和响应时用来交换信息的,还需要遵守规
定好的格式。
	
	作用:应用报文多是多个系统之间需要通信的时候,比如银行的ESB系统到网关系统再到
银联系统。在这中间报文就承担了装载数据,运输数据的功能,可能在这三个系统中报文的格
式互不相同,但是承载的数据都是一样的。

2.报文的发送

客户端:

目录

在这里插入图片描述

FaSong.java

package com.rj.bd.bj;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.UUID;

import com.rj.bd.utils.Dates;

/**
 * @desc 客户端--发送报文
 * @author HYZ
 * @time  2021年1月25日
 */
public class FaSong {
	public void sendMessage() throws IOException{
		try{
			System.out.println("===========开始发送报文============");
			HttpURLConnection servletConnection = createServletUrl();
			xmlWriteStream(servletConnection);
			getResponseResult(servletConnection);
		}catch (ConnectException e) {
			System.out.println("客户端与服务端连接异常,请再次尝试");
		}
	}
	
	
	/**
	 * @desc 创建客户端与服务端的连接并且设置发送报文的一些属性值
	 * @return
	 * @throws MalformedURLException
	 * @throws IOException
	 * @throws ProtocolException
	 */
	public HttpURLConnection createServletUrl() throws
	 MalformedURLException,IOException,ProtocolException{
		//接收报文的地址
		URL uploadServlet = new URL(" http://localhost:8089/BaoWenServer/xmlServlet.do ");
		HttpURLConnection servletConnection = (HttpURLConnection)
							 uploadServlet.openConnection();
		//设置连接参数
		servletConnection.setRequestMethod("POST");
		servletConnection.setDoOutput(true);
		servletConnection.setDoInput(true);
		servletConnection.setAllowUserInteraction(true);
		return servletConnection;
	}
	
	/**
	 * @desc 获取服务端反馈回来的结果
	 * @param servletConnection
	 * @throws IOException
	 */
	public void getResponseResult(HttpURLConnection servletConnection) throws
	 IOException{
		System.out.println("============**服务端的返回值**============");
		//获取返回的数据
		InputStream inputStream = servletConnection.getInputStream();//获取反馈回来的流
		//创建一个缓冲读取的reader对象
		BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
		//创建一个能够承接返回来指的sb
		StringBuffer sb = new StringBuffer();
		//创建一个能够临时存储读取一行信息的变量
		String strMessage = "";
		while((strMessage = reader.readLine()) != null){
			sb.append(strMessage);//将返回的流的信息逐行的压入到sb中
		}
		System.out.println("接收返回值:"+sb);
	}
	/**
	 * @desc 将xml转成流开始写入
	 * @param servletConnection
	 * @throws IOException 
	 */
	public void xmlWriteStream(HttpURLConnection servletConnection) throws IOException{
		//开启流,写入XML数据
		OutputStream output = servletConnection.getOutputStream();
		System.out.println("发送的报文:");
		String str = xmlToString();
		System.out.println(str);
		output.write(str.getBytes("UTF-8"));
		output.flush();
		output.close();
	}
	/**
	 * @desc 将xml报文转换成字符串
	 * @return
	 */
	@SuppressWarnings("static-access")
	public String xmlToString(){
		StringBuffer sendStr = new StringBuffer();
		sendStr.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
		
		sendStr.append("<request_data>");
		sendStr.append("<request_token>BCDBCD</request_token>");
		sendStr.append("<request_cardNum>62284801912705</request_cardNum>");
		sendStr.append("<request_name>张飞</request_name>");
		sendStr.append("<request_pass>123123</request_pass>");
		sendStr.append("<request_time>"+new Dates().CurrentYMDHSMTime()+
			"</request_time>");
		sendStr.append("<monery_count>200.00</monery_count>");
		sendStr.append("<shop_name>吉野家</shop_name>");
		sendStr.append("<shop_id>JYJ</shop_id>");
		sendStr.append("<sale_no>"+UUID.randomUUID().toString()+"</sale_no>");
		sendStr.append("</request_data>");
		String str = sendStr.toString();
		return str;
	}
}

CeShi.java

package com.rj.bd.bj;

import java.io.IOException;

/**
 * @desc 客户端--加载报文发送类
 * @author HYZ
 * @time  2021年1月25日
 */
public class CeShi {
	public static void main(String[] args) throws IOException {
		FaSong fs = new FaSong();
		fs.sendMessage();
	}
}

服务端:

目录

在这里插入图片描述

IXmlService.java

package com.rj.bd.xml;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Map;

/**
 * @desc XML解析M层接口
 * @author HYZ
 * @time  2021年1月25日
 */
public interface IXmlService {
	
Map<String, Object> queryInfo() throws ClassNotFoundException, SQLException;

Map<String, Object> queryUser(Map<String, Object> map) throws
	ClassNotFoundException, SQLException;

boolean saleInfo(Map<String, Object> map) throws 
	ClassNotFoundException, SQLException, FileNotFoundException, IOException;

}

XmlServiceImpl.java

package com.rj.bd.xml;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Map;

import com.rj.bd.dao.DaoImpl;
import com.rj.bd.dao.IDao;
/**
 * @desc  XML解析M层接口实现类
 * @author HYZ
 * @time  2021年1月25日
 */
public class XmlServiceImpl implements IXmlService{
	
IDao dao = new DaoImpl();

@Override
public Map<String, Object> queryInfo() throws ClassNotFoundException, SQLException {
	return dao.executeQueryForMap(" select * from info ");
}

@Override
public Map<String, Object> queryUser(Map<String, Object> map) throws 
ClassNotFoundException, SQLException {
	return dao.executeQueryForMap(" select * from user where name=? 
				and pass=? and cadNum=? ",
			new int []{Types.VARCHAR,Types.VARCHAR,Types.VARCHAR},
			new Object[]{map.get("request_name"),map.get("request_pass"),
				map.get("request_cardNum")});
}

@Override
public boolean saleInfo(Map<String, Object> map)
		throws ClassNotFoundException, SQLException, 
		FileNotFoundException, IOException {
	Map<String, Object> map_user = dao.executeQueryForMap(" select * from user where
		 name=? and pass=? and cadNum=? ",
			new int[]{Types.VARCHAR,Types.VARCHAR,Types.VARCHAR},
			new Object[]{map.get("request_name"),map.get("request_pass"),
				map.get("request_cardNum")});
	Map<String, Object> map_shop = dao.executeQueryForMap(" select * from shop 
		where shop_id=? ",
			new int[]{Types.VARCHAR},
			new Object[]{map.get("shop_id")});
	
	int kaNeiJinEr = (Integer) map_user.get("jinEr");
	String monery_count = (String) map.get("monery_count");//本次一共消费了多少钱
	System.out.println("---------monery_count-----------"+monery_count);
	int xiaoFeiJinEr = (int)Double.parseDouble((monery_count));
	int shopYuanYouDeJin = (Integer) map_shop.get("shop_jinEr");
	if (kaNeiJinEr >= xiaoFeiJinEr) {
		//1.消费者卡内的余额减少
		dao.executeUpdate(" update user set jinEr=? where name=? and pass=? 
			and cadNum=? ",
				new int[]{Types.INTEGER,Types.VARCHAR,Types.VARCHAR,Types.VARCHAR},
				new Object[]{(kaNeiJinEr-xiaoFeiJinEr),map.get("request_name"),
					map.get("request_pass"),map.get("request_cardNum")});
		//2.商家的金额增加
		dao.executeUpdate(" update shop set shop_jinEr=? where shop_id=? ",
				new int[]{Types.INTEGER,Types.VARCHAR},
				new Object[]{shopYuanYouDeJin+xiaoFeiJinEr,map.get("shop_id")});
		//3.产生一条消费记录
		dao.executeUpdate(" insert into mingxi(uid,shop_id,sale_no,mingxijiner) 
									values(?,?,?,?) ",
				new int[]{Types.VARCHAR,Types.VARCHAR,Types.VARCHAR,Types.INTEGER},
				new Object[]{map_user.get("uid"),map_shop.get("shop_id"),
					map.get("sale_no"),xiaoFeiJinEr});
		return true;
	}else {
		System.out.println("卡内金额不足......");
		System.exit(0);
		return false;
	}
}

}

XmlServlet.java

package com.rj.bd.xml;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import com.rj.bd.util.Dates;
/**
 * @desc   XML模块的C层
 * @author HYZ
 * @time  2021年1月25日
 */
@SuppressWarnings("serial")
public class XmlServlet extends HttpServlet{

@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
 throws ServletException, IOException {
	request.setCharacterEncoding("utf-8");
	response.setCharacterEncoding("utf-8");
	try {
		//-------通过request.getInputStream()获取输入的流--------
		final int BUFFER_SIZE = 8 * 1024 ;
		byte[] buffer = new byte[BUFFER_SIZE];
		ServletInputStream sis = request.getInputStream();
		System.out.println("sis:"+sis);
		
		int length = 0;
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		do{
			length = sis.read(buffer);
			if (length > 0) {
				baos.write(buffer,0,length);
			}
		}while (length * 2 == BUFFER_SIZE);
		String bodyData = new String(baos.toByteArray());
		System.out.println("------>"+bodyData);
		//----------通过request.getInputStream()获取输入的流-----------
		
		
		//1.初始化jdk中的用来解析xml的dom工厂
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		//2.获得具体的dom解析器
		DocumentBuilder db = dbf.newDocumentBuilder();
		//3.解析一个xml文档,获得Document对象(根节点)
		InputSource is = new InputSource(new StringReader(bodyData));
		Document document = null;
		try{
			document = db.parse(is);//将流转换成document对象
		}catch(Exception e){
			return;
		}
		
		//通过抓取根节点进而获取子节点
		NodeList list = document.getElementsByTagName("request_data");
		//将抓取之后获得到的值存在map中
		Map<String, Object> map = new HashMap<String,Object>();
		IXmlService service = new XmlServiceImpl();
		for (int i = 0; i < list.getLength(); i++) {
			//通过item(i)获取根节点下的每一个子节点
			Element element = (Element) list.item(i);
			//1.识别码
			String request_token = element.getElementsByTagName("request_token").item(0)
				.getFirstChild().getNodeValue();
			map.put("request_token", request_token);
			//2.卡号
			String request_cardNum = element.getElementsByTagName("request_cardNum")
				.item(0).getFirstChild().getNodeValue();
			map.put("request_cardNum", request_cardNum);
			//3.持卡人姓名
			String request_name = element.getElementsByTagName("request_name").item(0)
				.getFirstChild().getNodeValue();
			map.put("request_name", request_name);
			//4.该卡的密码
			String request_pass = element.getElementsByTagName("request_pass").item(0)
				.getFirstChild().getNodeValue();
			map.put("request_pass", request_pass);
			//5.本次消费请求的时间
			String request_time = element.getElementsByTagName("request_time").item(0)
				.getFirstChild().getNodeValue();
			map.put("request_time", request_time);
			//6.本次消费的金额
			String monery_count = element.getElementsByTagName("monery_count").item(0)
				.getFirstChild().getNodeValue();
			map.put("monery_count", monery_count);
			//7.本次消费到的商家的名字
			String shop_name = element.getElementsByTagName("shop_name").item(0)
				.getFirstChild().getNodeValue();
			map.put("shop_name", shop_name);
			//8.本次消费到的商家的id
			String shop_id = element.getElementsByTagName("shop_id").item(0)
				.getFirstChild().getNodeValue();
			map.put("shop_id", shop_id);
			//9.本次消费到的流水单号
			String sale_no = element.getElementsByTagName("sale_no").item(0)
				.getFirstChild().getNodeValue();
			map.put("sale_no", sale_no);
			
		}
		//客户端发送来的本息消费的明细请求
		String request_token = (String) map.get("request_token");
		String request_cardNum = (String) map.get("request_cardNum");
		String request_name = (String) map.get("request_name");
		String request_pass = (String) map.get("request_pass");
		String request_time = (String) map.get("request_time");
		String monery_count = (String) map.get("monery_count");
		String shop_name = (String) map.get("shop_name");
		String shop_id = (String) map.get("shop_id");
		String sale_no = (String) map.get("sale_no");
		
		//方便理解:
		System.out.println("本次的消费请求的明细为:"
				 +request_token+
			    "\t\t"+request_name+
			    "\t"+request_cardNum+
			    "\t"+request_pass+
				"\t"+request_time+
				"\t"+monery_count+
				"\t"+shop_name+
				"\t"+shop_id+
				"\t"+sale_no
				);	
		Map<String, Object> map_info = service.queryInfo();
		if (map_info.get("token").equals(request_token)) {
			//查询一个该用户所用的本次消费的卡的卡号和密码以及名字是否匹配
			Map<String, Object> map_user = service.queryUser(map);
			if (map_user != null ) {
				System.out.println("用户名密码与卡号正确");
				//进行刷卡消费处理
				boolean yn = service.saleInfo(map);
				if (yn) {
					System.out.println("本次消费完成");
					//要返回的报文
					StringBuffer resultBuffer = new StringBuffer();
					resultBuffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
					resultBuffer.append("<request_data>");
					
					resultBuffer.append("<request_name>"+request_name+
					"</request_name>");
					resultBuffer.append("<request_cardNum>"+request_cardNum+
						"</request_cardNum>");
					resultBuffer.append("<request_time>"+
						new Dates().CurrentYMDHSMTime()+"</request_time>");
					resultBuffer.append("<monery_count>"+monery_count+
						"</monery_count>");
					resultBuffer.append("<shop_name>"+shop_name+"</shop_name>");
					resultBuffer.append("<sale_no>"+sale_no+"</sale_no>");
					resultBuffer.append("<request_token>成功了</request_token>");
					
					resultBuffer.append("</request_data>");
					//设置发送报文的格式
					response.setContentType("text/xml");
					response.setCharacterEncoding("UTF-8");
					
					PrintWriter out = response.getWriter();
					out.println(resultBuffer.toString());
					out.flush();
					out.close();
				}
			}
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
}
	
}

数据库

IDao.java

package com.rj.bd.dao;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
/**
 * @desc 数据库连接对象
 * @author HYZ
 * @time  2021年1月25日
 */
public interface IDao {
	/**
     * 根据sql查询列表数据(查询一条),不支持预编译的方式
     * @param sql
     * @return
     * @throws ClassNotFoundException
     * @throws SQLException
     */
    public Map<String, Object> executeQueryForMap(String sql) 
    throws ClassNotFoundException, SQLException;
	/**
	 * 根据sql查询列表数据(查询一条),支持预编译的方式
	 * @param sql
	 * @param types
	 * @param ObjectValues
	 * @return
	 * @throws SQLException 
	 * @throws ClassNotFoundException 
	 */
	public Map<String, Object> executeQueryForMap
	(String sql , int[] types,Object[] values) 
	throws ClassNotFoundException, SQLException ;
    
	  /**
     * 根据sql查询列表数据(查询多条),不支持预编译的方式
     * @param sql
     * @return
     * @throws ClassNotFoundException
     * @throws SQLException
     */
    public List<Map<String, Object>> executeQueryForList(String sql)
     throws ClassNotFoundException, SQLException;
	/**
	 * 根据sql查询列表数据(查询多条),支持预编译的方式
	 * @param sql
	 * @param types
	 * @param ObjectValues
	 * @return
	 * @throws SQLException 
	 * @throws ClassNotFoundException 
	 */
	public List<Map<String, Object>> executeQueryForList
	(String sql , int[] types,Object[] values) throws 
	ClassNotFoundException, SQLException ;
    
	

    /**
     * 执行 增、删、改、等的操作,不支持预编译的方式
     * @param sql
     * @return
     * @throws ClassNotFoundException
     * @throws SQLException
     */
	public int executeUpdate(String sql) throws ClassNotFoundException, SQLException ;
	/**
	 * 预编译sql操作,   支持insert , update  , delete  语句
	 * @param sql
	 * @param types
	 * @param ObjectValues
	 * @return
	 * @throws SQLException 
	 * @throws ClassNotFoundException 
	 * @throws FileNotFoundException 
	 * @throws IOException 
	 */
	public int executeUpdate(String sql , int[] types,Object[] values)
	 throws ClassNotFoundException, SQLException, FileNotFoundException, IOException ;
	
	/**
	 * 预编译sql操作,   支持  select 语句
	 * @param sql
	 * @param types
	 * @param ObjectValues
	 * @return
	 * @throws SQLException 
	 * @throws ClassNotFoundException 
	 */
	public int executeQueryForInt(String sql ) throws 
	ClassNotFoundException, SQLException ;
	/**
	 * 预编译sql操作,   支持  select 语句
	 * @param sql
	 * @param types
	 * @param ObjectValues
	 * @return
	 * @throws SQLException 
	 * @throws ClassNotFoundException 
	 */
	public int executeQueryForInt
	(String sql , int[] types,Object[] values) 
	throws ClassNotFoundException, SQLException ;
}

DaoImpl.java

package com.rj.bd.dao;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @desc 数据库连接对象
 * @author HYZ
 * @time  2021年1月25日
 */
public class DaoImpl implements IDao {
	
	
	private String sDBDriver = "org.gjt.mm.mysql.Driver";
	//设置数据库名称为:pubs
	private String sConnStr =
		 "jdbc:mysql://localhost:3306/baowen?useUnicode=true&characterEncoding=utf-8";
    private String username = "root";  //登录数据库用户名
    private String password = "root";   //登录数据库密码

    
    /**
     * 建立连接
     * @return
     * @throws ClassNotFoundException
     * @throws SQLException
     */
    public Connection getConnection() throws ClassNotFoundException, SQLException{
    	
		 Class.forName(sDBDriver); //指定JDBC数据库驱动程序

		 return DriverManager.getConnection(sConnStr,username,password);
    }


	/**
     * 根据sql查询列表数据(查询一条),不支持预编译的方式
     * @param sql
     * @return
     * @throws ClassNotFoundException
     * @throws SQLException
     */
	public Map<String, Object> executeQueryForMap(String sql)
	throws ClassNotFoundException, SQLException {
		System.err.println("查询一条:"+sql);
    	Connection connect =this.getConnection();
		Statement stmt = connect.createStatement();
		ResultSet rs = stmt.executeQuery(sql);
		List<Map<String, Object>> list = this.rsToList(rs);
		if( !list.isEmpty() ){
			return list.get(0);
		}
		this.releaseConnection(rs, stmt, connect);//关闭连接
		return null;
	}

	/**
	 * 根据sql查询列表数据(查询一条),支持预编译的方式
	 * @param sql
	 * @param types
	 * @param values
	 * @return
	 * @throws SQLException 
	 * @throws ClassNotFoundException 
	 */
	public Map<String, Object> executeQueryForMap
	(String sql, int[] types,Object[] values) throws
	 SQLException, ClassNotFoundException  {
		System.err.println("查询一条:"+sql);
		this.print(values);
		Connection connect = this.getConnection();
		PreparedStatement pst =  connect.prepareStatement(sql);
		
		if( types != null ){
			for(int i=0;i<types.length;i++){
				switch( types[i] ){
				case Types.VARCHAR:
					pst.setString(i+1, String.valueOf( values[i] ) );
					break;
				case Types.INTEGER:
					pst.setInt(i+1, Integer.parseInt( String.valueOf( values[i] ) ));
					break;
				}
				
			}
		}

		ResultSet rs = pst.executeQuery();
		List<Map<String, Object>> list = this.rsToList(rs);
		if( !list.isEmpty() ){
			return list.get(0);
		}
		this.releaseConnection(rs, pst, connect);
		return null;
	}


	
    /**
     * 根据sql查询列表数据,不支持预编译的方式
     * @param sql
     * @return
     * @throws ClassNotFoundException
     * @throws SQLException
     */
    public List<Map<String, Object>> executeQueryForList(String sql) 
    throws ClassNotFoundException, SQLException{
    	System.err.println("查询多条:"+sql);
    	Connection connect =this.getConnection();
		Statement stmt = connect.createStatement();
		ResultSet rs = stmt.executeQuery(sql);
		List<Map<String, Object>> list = this.rsToList(rs);
		this.releaseConnection(rs, stmt, connect);//关闭连接
		return list;
	}

    /**
     * 执行 增、删、改、等的操作,不支持预编译的方式
     * @param sql
     * @return
     * @throws ClassNotFoundException
     * @throws SQLException
     */
	public int executeUpdate(String sql) throws ClassNotFoundException, SQLException {
		System.err.println("更新:"+sql);
		Connection connect=this.getConnection();
		Statement stmt=connect.createStatement();
		int count=stmt.executeUpdate(sql);

		this.releaseConnection(stmt, connect);//关闭连接
	
		return count;
	}
	
	
	/**
	 * 根据sql查询列表数据,支持预编译的方式
	 * @param sql
	 * @param types
	 * @param values
	 * @return
	 * @throws SQLException 
	 * @throws ClassNotFoundException 
	 */
	public List<Map<String, Object>> executeQueryForList
	(String sql , int[] types,Object[] values) throws
	 ClassNotFoundException, SQLException{
		System.err.println("查询多条:"+sql);	
		this.print(values);
		Connection connect = this.getConnection();
			PreparedStatement pst =  connect.prepareStatement(sql);
			
			if( types != null ){
				for(int i=0;i<types.length;i++){
					switch( types[i] ){
					case Types.VARCHAR:
						pst.setString(i+1, String.valueOf( values[i] ) );
						break;
					case Types.INTEGER:
						pst.setInt(i+1, Integer.parseInt( String.valueOf( values[i] ) ));
						break;
					}
					
				}
			}

			ResultSet rs = pst.executeQuery();
			List<Map<String, Object>> list = this.rsToList(rs);
			this.releaseConnection(rs, pst, connect);
			return list;
	}


	/**
	 * 预编译sql操作,   支持insert , update  , delete  语句
	 * @param sql
	 * @param types
	 * @param values
	 * @return
	 * @throws SQLException 
	 * @throws ClassNotFoundException 
	 * @throws IOException 
	 */
	public int executeUpdate(String sql , int[] types,Object[] values)
	 throws ClassNotFoundException, SQLException, IOException{
		System.err.println("更新:"+sql);
		this.print(values);
		Connection connect = this.getConnection();
		PreparedStatement pst =  connect.prepareStatement(sql);
		
		if( types != null ){
			for(int i=0;i<types.length;i++){
				switch( types[i] ){
				case Types.VARCHAR:
					pst.setString(i+1, String.valueOf( values[i] ) );
					break;
				case Types.INTEGER:
					pst.setInt(i+1, Integer.parseInt( String.valueOf( values[i] ) ));
					break;
				case Types.BLOB:
					InputStream in = new FileInputStream( (File)values[i] );
					pst.setBinaryStream(i+1, in , in.available()  );
					break;
				}
			}
		}

		int count = pst.executeUpdate();
		this.releaseConnection(pst, connect);
		return count;  
	}
	
	/**
	 * 查询一个整数,例如记录总数(不支持预编译)
	 * @param sql
	 * @param types
	 * @param values
	 * @return
	 * @throws SQLException 
	 * @throws ClassNotFoundException 
	 */
	public int executeQueryForInt(String sql) throws
	 ClassNotFoundException, SQLException{
		System.err.println("查询总数:"+sql);
		
    	Connection connect =this.getConnection();
		Statement stmt = connect.createStatement();
		ResultSet rs = stmt.executeQuery(sql);
		if(rs.next()){
			return rs.getInt(1);
		}
		this.releaseConnection(rs, stmt, connect);
		return 0; 
	}
	/**
	 * 查询一个整数,例如记录总数(支持预编译)
	 * @param sql
	 * @param types
	 * @param values
	 * @return
	 * @throws SQLException 
	 * @throws ClassNotFoundException 
	 */
	public int executeQueryForInt(String sql , int[] types,Object[] values)
	 throws ClassNotFoundException, SQLException{
		System.err.println("查询总数:"+sql);
		this.print(values);
		Connection connect = this.getConnection();
		PreparedStatement pst =  connect.prepareStatement(sql);
		
		if( types != null ){
			for(int i=0;i<types.length;i++){
				switch( types[i] ){
				case Types.VARCHAR:
					pst.setString(i+1, String.valueOf( values[i] ) );
					break;
				case Types.INTEGER:
					pst.setInt(i+1, Integer.parseInt( String.valueOf( values[i] ) ));
					break;
				}
				
			}
		}

		ResultSet rs = pst.executeQuery();
		if(rs.next()){
			return rs.getInt(1);
		}
		this.releaseConnection(rs, pst, connect);
		return 0; 
	}
	/**
	 * 将ResultSet中的结果包装成list中装Map的结构
	 * @author 		wyh
	 * @time		2016--07--18
	 * @param		 rs
	 * @return
	 * @throws SQLException
	 */
	private List<Map<String, Object>> rsToList( ResultSet rs ) throws SQLException{
		List<Map<String, Object>> row = new ArrayList<Map<String, Object>>();
		 while (rs.next()) {
			 Map<String, Object> col = new HashMap<String, Object>();
			 for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) {
				 //System.out.println(  rs.getMetaData().getColumnType(i)  );
				 switch( rs.getMetaData().getColumnType(i) ){
			 	 case Types.VARCHAR:
			 		col.put(rs.getMetaData().getColumnName(i), rs.getString(i));
			 		break;
			 	 case Types.INTEGER:
				 	col.put(rs.getMetaData().getColumnName(i), rs.getInt(i));
				 	break;	
			 	 case Types.BLOB:
			 		InputStream in = rs.getBinaryStream(i);

				 	col.put(rs.getMetaData().getColumnName(i), in );
				 	break;	
				 default:
					 col.put(rs.getMetaData().getColumnName(i), rs.getString(i));
				 	break;	
				 }
				 
			 }
			row.add(col);
		}
		 return row;
	}
	
	/**
	 * 打印出所有的参数值
	 * @param values
	 */
	private void print(Object[] values){
		if( values == null ) return;
		System.out.println("参数值:\t---------------------");
		for (int i = 0; i < values.length; i++) {
			System.out.println( "\t["+i+"]=["+values[i]+"]" );
		}
		System.out.println("\t---------------------");
	}
	
	
	@SuppressWarnings("unused")
	private void releaseConnection(Connection connect) throws SQLException{
	    try {
	        if (connect != null && !connect.isClosed()){
	        	connect.close();
	        }
	    } catch (SQLException se){
	        System.out.println("Close the connection encounter error!\n" +
	        	 se.getMessage());
	        throw new SQLException("关闭连接异常!");
	    }
	}
	
	private void releaseConnection(Statement stmt, Connection connect) 
	throws SQLException{
	    try {
	        if (stmt != null){
	        	stmt.close();
	        }
	        if (connect != null && !connect.isClosed()){
	        	connect.close();
	        }
	    } catch (SQLException se){
	        System.out.println("Close the connection encounter error!\n" + 
	        	se.getMessage());
	        throw new SQLException("关闭连接异常!");
	    }
	}
	private void releaseConnection(PreparedStatement pst, Connection connect)
	 throws SQLException{
	    try {
	        if (pst != null){
	            pst.close();
	        }
	        if (connect != null && !connect.isClosed()){
	        	connect.close();
	        }
	    } catch (SQLException se){
	        System.out.println("Close the connection encounter error!\n" + 
	        	se.getMessage());
	        throw new SQLException("关闭连接异常!");
	    }
	}
	
	private void releaseConnection(ResultSet rs, Statement stmt, Connection connect)
	 throws SQLException{
	    try {
	        if (rs != null){
	            rs.close();
	        }
	        if (stmt != null){
	        	stmt.close();
	        }
	        if (connect != null && !connect.isClosed()){
	        	connect.close();
	        }
	    } catch (SQLException se){
	        System.out.println("Close the connection encounter error!\n" + 
	        	se.getMessage());
	        throw new SQLException("关闭连接异常!");
	    }
	}
	private void releaseConnection
		(ResultSet rs, PreparedStatement pst, Connection connect)
		 throws SQLException{
	    try {
	        if (rs != null){
	            rs.close();
	        }
	        if (pst != null){
	            pst.close();
	        }
	        if (connect != null && !connect.isClosed()){
	        	connect.close();
	        }
	    } catch (SQLException se){
	        System.out.println("Close the connection encounter error!\n" +
	        	 se.getMessage());
	        throw new SQLException("关闭连接异常!");
	    }
	}
	


		
		
	public static void main(String[] args) throws
	 ClassNotFoundException, SQLException, IOException {
		
		DaoImpl dao = new DaoImpl();
		int[] types1 = {Types.VARCHAR};
		String[] objValues1 = {"%"};
		
		
		List<Map<String, Object>> list = 
			dao.executeQueryForList("select * from  jobs where job_desc like ?",
				 types1, objValues1);
		
		System.out.println("list.size()==="+list.size());
		for (int i = 0; i < list.size(); i++) {
			System.out.println(  list.get(i) );
		}
	}
}

工具类:

客户端:

Dates.java

在这里插入图片描述

服务端:

Dates.java(同上)

JAXBUtil.java

在这里插入图片描述

​ RequestData.java

在这里插入图片描述

jar包:

mysql-connector-java-3.1.13-bin.jar

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值