Spring MVC接受XML格式的数据
来源:互联网 发布:mac系统剪切文件 编辑:程序博客网 时间:2024/05/22 14:46
代码:
sendxml.jsp
- <%@ page language="java" contentType="text/html; charset=UTF-8"
- pageEncoding="UTF-8"%>
- <!DOCTYPE html>
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <title>测试接收XML格式的数据</title>
- <script type="text/javascript" src="js/jquery-1.11.0.min.js"></script>
- <script type="text/javascript" src="js/json2.js"></script>
- <script type="text/javascript">
- $(document).ready(function(){
- sendxml();
- });
-
- function sendxml(){
- var xmlData = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><book><id>1</id><name>疯狂Java讲义</name><author>李刚</author></book>";
- $.ajax("${pageContext.request.contextPath}/sendxml",// 发送请求的URL字符串。
- {
- type : "POST", // 请求方式 POST或GET
- contentType:"application/xml", // 发送信息至服务器时的内容编码类型
- // 发送到服务器的数据。
- data: xmlData,
- async: true , // 默认设置下,所有请求均为异步请求。如果设置为false,则发送同步请求
- });
- }
- </script>
- </head>
- <body>
-
- </body>
- </html>
Book.java
- package com.bean;
-
- import java.io.Serializable;
- import javax.xml.bind.annotation.XmlElement;
- import javax.xml.bind.annotation.XmlRootElement;
-
-
- @XmlRootElement
- public class Book implements Serializable {
- private Integer id;
- private String name;
- private String author;
- public Book() {
- super();
-
- }
- public Book(Integer id, String name, String author) {
- super();
- this.id = id;
- this.name = name;
- this.author = author;
- }
- public Integer getId() {
- return id;
- }
-
- @XmlElement
- public void setId(Integer id) {
- this.id = id;
- }
-
- public String getName() {
- return name;
- }
- @XmlElement
- public void setName(String name) {
- this.name = name;
- }
-
- public String getAuthor() {
- return author;
- }
- @XmlElement
- public void setAuthor(String author) {
- this.author = author;
- }
-
- @Override
- public String toString() {
- return "Book [id=" + id + ", name=" + name + ", author=" + author + "]";
- }
-
- }
BookController.java
- package com.control;
-
- import org.apache.commons.logging.Log;
- import org.apache.commons.logging.LogFactory;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestBody;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RequestMethod;
-
- import com.bean.Book;
-
- @Controller
- public class BookController {
- private static final Log logger = LogFactory.getLog(BookController.class);
-
-
- @RequestMapping(value="/sendxml", method=RequestMethod.POST)
- public void sendxml(@RequestBody Book book){
- logger.info(book);
- logger.info("接受XML数据成功!");
- }
- }
截图:
0 0