rest入门实践之三:
第一步:建立webservice
第二步:后台代码:
1 @Path("hello") 2 public class HelloXml { 3 4 @GET 5 @Path("getHelloXml") 6 @Produces("application/xml") 7 @Consumes("text/plain") 8 public String getHelloXml(@DefaultValue("1") @QueryParam("id") String id) throws Exception { 9 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 10 DocumentBuilder dBuilder = factory.newDocumentBuilder(); 11 Document document = dBuilder.newDocument(); 12 13 14 //模拟 15 Element root = document.createElement("湖北省"); 16 17 root.appendChild(document.createElement("武汉市")); 18 root.appendChild(document.createElement("襄樊市")); 19 20 root.setAttribute("id", id); 21 22 document.appendChild(root); 23 24 //输出 25 StringWriter strWtr = new StringWriter(); 26 StreamResult strResult = new StreamResult(strWtr); 27 TransformerFactory tfac = TransformerFactory.newInstance(); 28 Transformer t = tfac.newTransformer(); 29 t.transform(new DOMSource(document.getDocumentElement()),strResult); 30 String result = strResult.getWriter().toString(); 31 System.out.println(result); 32 return result; 33 } 34 }
第三步:启动服务: 访问:http://localhost/RestPractice3/services/hello/getHelloXml?id=4
第四步:结果: