Spring MVC返回XML格式的数据

 代码:

readxml.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>




测试返回XML格式的数据





编号 书名 作者

book.xml



	1
	Spring MVC企业应用实战
	海哥


Book.java

package com.bean;

import java.io.Serializable;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

// @XmlRootElement表示XML文档的根元素
@XmlRootElement
public class Book implements Serializable {
	private Integer id;
	private String name;
	private String author;
	public Book() {
		super();
		// TODO Auto-generated constructor stub
	}
	public Book(Integer id, String name, String author) {
		super();
		this.id = id;
		this.name = name;
		this.author = author;
	}
	public Integer getId() {
		return id;
	}
	// 该属性作为xml的element
	@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 java.io.InputStream;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.bean.*;
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 org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class BookController {
	
	private static final Log logger = LogFactory.getLog(BookController.class);
	 
	// @RequestBody Book book会将传递的xml数据自动绑定到Book对象
	 @RequestMapping(value="/sendxml", method=RequestMethod.POST)  
	 public void sendxml(@RequestBody Book book) {  
		 logger.info(book);
		 logger.info("接收XML数据成功");
	 }  
	 
	// @ResponseBody 会将Book自动转成XML数据返回
	 @RequestMapping(value="/readxml", method=RequestMethod.POST)  
	 public @ResponseBody Book readXml()throws Exception { 
		 // 通过JAXBContext的newInstance方法,传递一个class就可以获得一个上下文
		 JAXBContext context = JAXBContext.newInstance(Book.class);  
		 // 创建一个Unmarshall对象
		 Unmarshaller unmar = context.createUnmarshaller();  
		 InputStream is = this.getClass().getResourceAsStream("/book.xml");
		 // Unmarshall对象的unmarshal方法可以进行xml到Java对象的转换
		 Book book = (Book) unmar.unmarshal(is);  
		 logger.info(book); 
    	 return book;
	 }  
}

截图:


你可能感兴趣的:(Spring,MVC)