javaweb收藏编程SpringFramework

SpringMVC @ResponseBody和@Request

2016-08-19  本文已影响46132人  tenlee

@ResponseBody用法

作用:

使用时机:

配置返回JSON和XML数据

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.8.1</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.8.1</version>
</dependency>
 @RequestMapping("/testResponseBody")
    public @ResponseBody
    Person testResponseBody() {
        Person p = new Person();
        p.setName("xiaohong");
        p.setAge(12);
        return p;
    }

Person类

@XmlRootElement(name = "Person")
public class Person {
    private String name;
    private int age;
    public String getName() { return name;    }
    @XmlElement
    public void setName(String name) { this.name = name;    }
    public int getAge() { return age;    }
    @XmlElement
    public void setAge(int age) { this.age = age;    }
}
$.ajax({
    url: "testResponseBody",
    type: 'GET',
    headers: {
        Accept: "application/xml",
//        Accept:"application/json",
    },
    success: function(data, textStatus){
        console.log(data);
        alert(data);
    },
    error: function (data, textStatus, errorThrown) {
        console.log(data);
    },
        });

分析

用此注解或者ResponseEntity等类似类, 会导致response header含有accept-charset这个字段,而这个字段对于响应头是没有用的,以下方法可以关掉

<mvc:annotation-driven>
        <mvc:async-support default-timeout="3000"/>
        <!-- utf-8编码 -->
        <mvc:message-converters register-defaults="true">
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <constructor-arg value="UTF-8"/>
                <property name="writeAcceptCharset" value="false"/>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

@RequestBody使用

作用:

使用时机:

如何使用

其他代码同上, 配置Controller,如下:

@RequestMapping(value = "/testRequestBody", method= RequestMethod.POST)
    @ResponseBody
    public Person testRequestBody(@RequestBody Person p) {
        System.out.println("creating a employee:" + p);
        return p;
    }

Ajax代码如下:

 $.ajax({
    url: "testRequestBody",
    data: '{"name":"小红","age":12}', //要用双引号!!
    contentType: "application/json;charset=utf-8", // 因为上面是JSON数据

    type: "POST",
    headers: {
//                Accept: "application/xml",
        Accept: "application/json",
    },
    success: function(data, textStatus){
        console.log(data);
        alert(data);
    },
    error: function (data, textStatus, errorThrown) {
        console.log(data);
    },
});

xml类似.

总结

推荐阅读

解析Spring中的ResponseBody和RequestBody

上一篇 下一篇

猜你喜欢

热点阅读