Spring MVC返回XML格式的数据

代码:

readxml.jsp

[html]  view plain  copy
  1. <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>  
  2. <!DOCTYPE html>  
  3. <html>  
  4. <head>  
  5. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
  6. <title>测试返回XML格式的数据</title>  
  7. <script type="text/javascript" src="js/jquery-1.11.0.min.js"></script>  
  8. <script type="text/javascript" src="js/json2.js"></script>  
  9. <script type="text/javascript">  
  10. $(document).ready(function(){  
  11.     readxml();  
  12. });  
  13. function readxml(){  
  14.     $.ajax("${pageContext.request.contextPath}/readxml",// 发送请求的URL字符串。  
  15.             {  
  16.             dataType : "text", // 预期服务器返回的数据类型。  
  17.             type : "POST", //  请求方式 POST或GET  
  18.             async:  true , // 默认设置下,所有请求均为异步请求。如果设置为false,则发送同步请求  
  19.             // 请求成功后的回调函数。  
  20.             success :function(xml){  
  21.                 // 获得xml数据的id,name,author  
  22.                 var id = $("id", xml).text();  
  23.                 var name = $("name", xml).text();  
  24.                 var author = $("author", xml).text();  
  25.                 var tr  = $("<tr align='center'/>");  
  26.                 $("<td/>").html(id).appendTo(tr);  
  27.                 $("<td/>").html(name).appendTo(tr);  
  28.                 $("<td/>").html(author).appendTo(tr);  
  29.                 $("#booktable").append(tr);  
  30.            },  
  31.            // 请求出错时调用的函数  
  32.            error:function(){  
  33.                alert("数据接收失败");  
  34.            }  
  35.     });  
  36. }  
  37. </script>  
  38. </head>  
  39. <body>  
  40. <table id="booktable" border="1"  style="border-collapse: collapse;">  
  41.     <tr align="center">  
  42.       <th>编号</th>  
  43.       <th>书名</th>  
  44.       <th>作者</th>  
  45.     </tr>  
  46. </table>  
  47. </body>  
  48. </html>  

book.xml

[html]  view plain  copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <book>  
  3.     <id>1</id>  
  4.     <name>Spring MVC企业应用实战</name>  
  5.     <author>海哥</author>  
  6. </book>  

Book.java

[java]  view plain  copy
  1. package com.bean;  
  2.   
  3. import java.io.Serializable;  
  4. import javax.xml.bind.annotation.XmlElement;  
  5. import javax.xml.bind.annotation.XmlRootElement;  
  6.   
  7. // @XmlRootElement表示XML文档的根元素  
  8. @XmlRootElement  
  9. public class Book implements Serializable {  
  10.     private Integer id;  
  11.     private String name;  
  12.     private String author;  
  13.     public Book() {  
  14.         super();  
  15.         // TODO Auto-generated constructor stub  
  16.     }  
  17.     public Book(Integer id, String name, String author) {  
  18.         super();  
  19.         this.id = id;  
  20.         this.name = name;  
  21.         this.author = author;  
  22.     }  
  23.     public Integer getId() {  
  24.         return id;  
  25.     }  
  26.     // 该属性作为xml的element  
  27.     @XmlElement  
  28.     public void setId(Integer id) {  
  29.         this.id = id;  
  30.     }  
  31.   
  32.     public String getName() {  
  33.         return name;  
  34.     }  
  35.     @XmlElement  
  36.     public void setName(String name) {  
  37.         this.name = name;  
  38.     }  
  39.   
  40.     public String getAuthor() {  
  41.         return author;  
  42.     }  
  43.     @XmlElement  
  44.     public void setAuthor(String author) {  
  45.         this.author = author;  
  46.     }  
  47.   
  48.     @Override  
  49.     public String toString() {  
  50.         return "Book [id=" + id + ", name=" + name + ", author=" + author + "]";  
  51.     }  
  52.   
  53. }  

BookController.java

[java]  view plain  copy
  1. package com.control;  
  2. import java.io.InputStream;  
  3. import javax.xml.bind.JAXBContext;  
  4. import javax.xml.bind.Unmarshaller;  
  5. import org.apache.commons.logging.Log;  
  6. import org.apache.commons.logging.LogFactory;  
  7. import com.bean.*;  
  8. import org.springframework.stereotype.Controller;  
  9. import org.springframework.web.bind.annotation.RequestBody;  
  10. import org.springframework.web.bind.annotation.RequestMapping;  
  11. import org.springframework.web.bind.annotation.RequestMethod;  
  12. import org.springframework.web.bind.annotation.ResponseBody;  
  13.   
  14. @Controller  
  15. public class BookController {  
  16.       
  17.     private static final Log logger = LogFactory.getLog(BookController.class);  
  18.        
  19.     // @RequestBody Book book会将传递的xml数据自动绑定到Book对象  
  20.      @RequestMapping(value="/sendxml", method=RequestMethod.POST)    
  21.      public void sendxml(@RequestBody Book book) {    
  22.          logger.info(book);  
  23.          logger.info("接收XML数据成功");  
  24.      }    
  25.        
  26.     // @ResponseBody 会将Book自动转成XML数据返回  
  27.      @RequestMapping(value="/readxml", method=RequestMethod.POST)    
  28.      public @ResponseBody Book readXml()throws Exception {   
  29.          // 通过JAXBContext的newInstance方法,传递一个class就可以获得一个上下文  
  30.          JAXBContext context = JAXBContext.newInstance(Book.class);    
  31.          // 创建一个Unmarshall对象  
  32.          Unmarshaller unmar = context.createUnmarshaller();    
  33.          InputStream is = this.getClass().getResourceAsStream("/book.xml");  
  34.          // Unmarshall对象的unmarshal方法可以进行xml到Java对象的转换  
  35.          Book book = (Book) unmar.unmarshal(is);    
  36.          logger.info(book);   
  37.          return book;  
  38.      }    
  39. }  

截图:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

潇潇雨歇_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值