SpringMVC自定义返回XML/JSON数据

1、添加jackson依赖

compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.9.0'

2、开启 注解

3、编写JavaBean

package cn.bjut.entity;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Person {
    private String name;
    private int age;

    public Person() {
    }

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

4、编写Controller

    @ResponseBody
    @RequestMapping(value = "/json", method = RequestMethod.GET)
    public Person test1() {
        Person person = new Person();
        person.setAge(25);
        person.setName("你大爷");
        return person;
    }
  • 如果没有配置Person类的@XmlRootElement注解,那么只会返回JSON数据,无论Accept是什么
  • 如果配置了Person类的XML注解,那么如果Accept含有applicatin/xml, 就会返回xml数据
    因为浏览器默认包含了Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8 所以直接访问会返回XML数据
  • 如果改为accept: "application/json",即可返回JSON数据
  • 也可以通过指定URI后缀的方式来改变
    • http://localhost:8080/SpringMVCDemo/json.json 返回JSON数据
    • http://localhost:8080/SpringMVCDemo/json.xml 返回XML数据

SpringMVC自定义返回XML/JSON数据_第1张图片

你可能感兴趣的:(SpringMVC,SSM学习笔记)