Skip to content

Instantly share code, notes, and snippets.

@yanhua365
Last active December 28, 2015 09:29
Show Gist options
  • Save yanhua365/7478994 to your computer and use it in GitHub Desktop.
Save yanhua365/7478994 to your computer and use it in GitHub Desktop.
Spring MVC 3.1 的RequestMapping注解里增加了produces属性, 可以明确指定返回响应的格式为特定的格式,比如XML格式。
@RequestMapping(value = "/only-xml-response", method = RequestMethod.GET, produces = MediaType.APPLICATION_XML_VALUE)
@ResponseBody
public Object onlyXml(ModelMap modelMap){
//BookDTO 是增加了JAXB注解的一个JavaBean
BookDTO b = new BookDTO("Java in Action");
return b;
//也可以返回字符串
//return "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><book><name>java in action.</name></book>";
}
@yanhua365
Copy link
Author

BookDTO的代码是这样的:

@XmlRootElement(name="book")
public class BookDTO {

    String name;


    public BookDTO() {
    }

    public BookDTO(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    @XmlElement
    public void setName(String name) {
        this.name = name;
    }

}

@yanhua365
Copy link
Author

JAXB in JDK6
JAXB is included in JDK6, so, you do not need to include JAXB library manually, as long as object is annotated with JAXB annotation, Spring will convert it into XML format automatically.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment