标签:
直接采用的是模拟形式的http的post形式接口调用,采用servlet来做为服务端调用。
一、配置servlet
项目目录
api包用来存放封装和解析xml的两个工具类,servlet包用来存放单独接口,bean用来存放xml标记bean(@XmlRootElement采用标签转化)。后续想做成接口服务框架,直接单独返回object来进行接口调用。
mysql.jar:连接mysql驱动包
servlet配置:
二、xml的对象转化
xml转object:
1 public class UnMarshal { 2 3 public static Object xmltoobject(Object object,String xmlstr) throws Exception{ 4 JAXBContext context=JAXBContext.newInstance(object.getClass()); 5 Unmarshaller unmarsharller=context.createUnmarshaller(); 6 StringReader sr=new StringReader(xmlstr); 7 return unmarsharller.unmarshal(sr); 8 } 9 10 }
object转为xml:
1 public class Marshal { 2 3 public static String objecttoxml(Object object) throws Exception{ 4 Class<?> clazz=null; 5 clazz=object.getClass(); 6 //反射机制 获取JAXBContext对象 7 JAXBContext context =JAXBContext.newInstance(clazz); 8 //创建Marshaller对象 9 Marshaller marshaller=context.createMarshaller(); 10 StringWriter writer=new StringWriter(); 11 //将object转为xml 12 marshaller.marshal(object, writer); 13 return writer.toString(); 14 } 15 16 }
三、设置bean(JAXB标签标记转化xml)
详细可以参考这篇博文:http://desert3.iteye.com/blog/1570092
单独bean:
1 package com.mdf.api.bean; 2 3 import javax.xml.bind.annotation.XmlElement; 4 import javax.xml.bind.annotation.XmlRootElement; 5 6 @XmlRootElement(name="Test") 7 public class TestBean { 8 private int id; 9 private String name; 10 public int getId() { 11 return id; 12 } 13 @XmlElement 14 public void setId(int id) { 15 this.id = id; 16 } 17 public String getName() { 18 return name; 19 } 20 @XmlElement 21 public void setName(String name) { 22 this.name = name; 23 } 24 25 }
list形式(以数组形式封装):
1 package com.mdf.api.bean; 2 3 import javax.xml.bind.annotation.XmlElement; 4 import javax.xml.bind.annotation.XmlRootElement; 5 6 @XmlRootElement(name="TestBeanList") 7 public class TestBeanList { 8 9 private TestBean[] testbeans=null; 10 11 public TestBean[] getTestbeans() { 12 return testbeans; 13 } 14 @XmlElement 15 public void setTestbeans(TestBean[] testbeans) { 16 this.testbeans = testbeans; 17 } 18 19 }
四:服务端调用类 servlet形式
1 package com.mdf.api.servlet; 2 3 import java.io.BufferedReader; 4 import java.io.ByteArrayOutputStream; 5 import java.io.IOException; 6 import java.io.InputStream; 7 import java.io.InputStreamReader; 8 import java.io.PrintWriter; 9 import java.sql.Connection; 10 import java.sql.DriverManager; 11 import java.sql.PreparedStatement; 12 import java.sql.ResultSet; 13 import java.sql.SQLException; 14 import java.util.ArrayList; 15 import java.util.List; 16 17 import javax.servlet.ServletConfig; 18 import javax.servlet.ServletException; 19 import javax.servlet.annotation.WebServlet; 20 import javax.servlet.http.HttpServlet; 21 import javax.servlet.http.HttpServletRequest; 22 import javax.servlet.http.HttpServletResponse; 23 24 import com.mdf.api.Marshal; 25 import com.mdf.api.UnMarshal; 26 import com.mdf.api.bean.TestBean; 27 import com.mdf.api.bean.TestBeanList; 28 29 /** 30 * Servlet implementation class TestServlet 31 */ 32 @WebServlet("/TestServlet") 33 public class TestServlet extends HttpServlet { 34 private static final long serialVersionUID = 1L; 35 36 /** 37 * @see HttpServlet#HttpServlet() 38 */ 39 public TestServlet() { 40 super(); 41 // TODO Auto-generated constructor stub 42 } 43 44 /** 45 * @see Servlet#init(ServletConfig) 46 */ 47 public void init(ServletConfig config) throws ServletException { 48 // TODO Auto-generated method stub 49 } 50 51 /** 52 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse 53 * response) 54 */ 55 protected void doGet(HttpServletRequest request, HttpServletResponse response) 56 throws ServletException, IOException { 57 // TODO Auto-generated method stub 58 /* 59 * response.getWriter().append("Served at: " 60 * ).append(request.getContextPath()); 61 */ 62 doPost(request, response); 63 } 64 65 /** 66 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse 67 * response) 68 */ 69 protected void doPost(HttpServletRequest request, HttpServletResponse response) 70 throws ServletException, IOException { 71 72 Connection conn = null; 73 PreparedStatement psmt = null; 74 ResultSet rs = null; 75 String mysqlurl = "jdbc:mysql://localhost:3306/test?" 76 + "user=root&password=root&useUnicode=true&characterEncoding=UTF8"; 77 StringBuffer sqlstr = null; 78 InputStream is = null; //InputStream用来获取客户端请求 79 PrintWriter printwriter = null; //response输出 80 BufferedReader reader = null; // 缓冲读取 81 StringBuilder sb = null; // 用于存放流输出的string对象 82 String readline = null; 83 int i = -1; 84 TestBean rtestbean = null; 85 String requeststr = null; 86 List<TestBean> testbeans = null; 87 TestBeanList tbl=null; 88 ByteArrayOutputStream bos = null; 89 String xmlstr=null; 90 91 // 获取客户端传来请求参数 92 is = request.getInputStream(); // 获取输入流 93 bos = new ByteArrayOutputStream(); 94 while ((i = is.read()) != -1) { 95 bos.write(i); 96 } 97 98 requeststr = bos.toString(); 99 // 将xml解析,转为bean 100 rtestbean = new TestBean(); 101 try { 102 rtestbean = (TestBean) UnMarshal.xmltoobject(rtestbean, requeststr); 103 } catch (Exception e) { 104 // TODO Auto-generated catch block 105 e.printStackTrace(); 106 } 107 108 // 数据库连接获取数据对象 109 try { 110 Class.forName("com.mysql.jdbc.Driver"); 111 conn = DriverManager.getConnection(mysqlurl); 112 testbeans=new ArrayList<TestBean>(); 113 tbl=new TestBeanList(); 114 sqlstr=new StringBuffer(); 115 sqlstr.append("SELECT ID,NAME FROM TEST"); 116 if(rtestbean.getId()!=0){ 117 sqlstr.append(" WHERE ID=?"); 118 psmt = conn.prepareStatement(sqlstr.toString()); 119 psmt.setInt(1, rtestbean.getId()); 120 }else{ 121 psmt = conn.prepareStatement(sqlstr.toString()); 122 } 123 rs = psmt.executeQuery(); 124 while (rs.next()) { 125 TestBean testbean=new TestBean(); 126 testbean.setId(rs.getInt("ID")); 127 testbean.setName(rs.getString("NAME")); 128 testbeans.add(testbean); 129 } 130 tbl.setTestbeans(testbeans.toArray(new TestBean[testbeans.size()])); 131 } catch (Exception e) { 132 // TODO Auto-generated catch block 133 e.printStackTrace(); 134 }finally{ 135 if(rs!=null){ 136 try { 137 rs.close(); 138 } catch (SQLException e) { 139 // TODO Auto-generated catch block 140 e.printStackTrace(); 141 } 142 rs=null; 143 } 144 if(psmt!=null){ 145 try { 146 psmt.close(); 147 } catch (SQLException e) { 148 // TODO Auto-generated catch block 149 e.printStackTrace(); 150 } 151 psmt=null; 152 } 153 if(conn!=null){ 154 try { 155 conn.close(); 156 } catch (SQLException e) { 157 // TODO Auto-generated catch block 158 e.printStackTrace(); 159 } 160 conn=null; 161 } 162 } 163 164 //解析对象为xml 165 try { 166 xmlstr=Marshal.objecttoxml(tbl); 167 } catch (Exception e) { 168 // TODO Auto-generated catch block 169 e.printStackTrace(); 170 } 171 172 // PrintWriter返回给客户端 173 response.setCharacterEncoding("utf-8"); 174 printwriter = response.getWriter(); 175 printwriter.println(xmlstr.toString()); 176 printwriter.flush(); 177 printwriter.close(); 178 } 179 }
1 package com.mdf.apiclient; 2 3 import java.io.BufferedReader; 4 import java.io.BufferedWriter; 5 import java.io.ByteArrayOutputStream; 6 import java.io.IOException; 7 import java.io.InputStream; 8 import java.io.InputStreamReader; 9 import java.io.OutputStream; 10 import java.io.OutputStreamWriter; 11 import java.net.HttpURLConnection; 12 import java.net.MalformedURLException; 13 import java.net.URL; 14 15 public class main { 16 17 public static void main(String[] args) { 18 // TODO Auto-generated method stub 19 String url="http://localhost:8080/ApiServerDemo/ApiServlet"; 20 String content="<Test><id>3</id></Test>"; 21 HttpURLConnection urlconn=null; 22 OutputStream outputstream=null; 23 OutputStreamWriter osw=null; 24 BufferedWriter bw=null; 25 InputStream inputstream=null; 26 ByteArrayOutputStream bos=null; 27 BufferedReader reader=null; 28 byte[] data=null; 29 int readsize=0; 30 31 try { 32 urlconn=(HttpURLConnection)new URL(url).openConnection(); 33 //System.out.println(urlconn); 34 urlconn.setDoOutput(true); 35 urlconn.setRequestMethod("POST"); 36 urlconn.setRequestProperty("Content-Type","application/octet-stream;charset=utf-8"); 37 38 outputstream=urlconn.getOutputStream(); 39 osw=new OutputStreamWriter(outputstream,"utf-8"); 40 bw=new BufferedWriter(osw); 41 bw.write(content); 42 bw.flush(); 43 outputstream.flush(); 44 45 inputstream=urlconn.getInputStream(); 46 reader=new BufferedReader(new InputStreamReader(inputstream,"utf-8")); 47 String str=reader.readLine(); 48 System.out.println(str); 49 }catch (Exception e) { 50 // TODO Auto-generated catch block 51 e.printStackTrace(); 52 }finally{ 53 if(inputstream!=null){ 54 try { 55 inputstream.close(); 56 } catch (IOException e) { 57 // TODO Auto-generated catch block 58 e.printStackTrace(); 59 } 60 inputstream=null; 61 } 62 if(outputstream!=null){ 63 try { 64 outputstream.close(); 65 } catch (IOException e) { 66 // TODO Auto-generated catch block 67 e.printStackTrace(); 68 } 69 } 70 if(urlconn!=null){ 71 urlconn.disconnect(); 72 } 73 } 74 75 } 76 77 78 }
返回结果(结果为xml形式,可能没有格式化比较乱):
1 <?xml version="1.0" encoding="UTF-8" standalone="yes"?><TestBeanList><testbeans><id>3</id><name>胡金华</name></testbeans></TestBeanList>
我是个起步比较晚的“大龄码农”,身处四线小城市,技术上的成长和工作机会比较少。本来干着实施运维的活混着日子,但是实在苦闷而且无奈(主要是工资提不上去了,受到领导轻视,咽不下一口气),所以以28高龄继续走上码农之路。写的文章可能还很稚嫩,技术上总结也不到位,或者也可能也有错误,请各位大牛能够抽空指出,一定虚心改正。
标签:
原文地址:http://www.cnblogs.com/Nouno/p/5733874.html