Spring MVC 的 Controller 处理 AJAX 请求很简单,只需要在方法的前面加上 @ResponseBody
即可。
Controller 的方法一般返回 String(可以是JSON, XML, 普通的 Text),也可以是对象。
返回 Json 字符串
Controller 中添加方法
1
2
3
4
5
// 处理 AJAX 请求,返回响应的内容,而不是 View Name
public String ajaxString() {
return "{\"username\": \"Josh\", \"password\": \"Passw0rd\"}";
}-
输出:
{username: "Josh", password: "Passw0rd"}
自动转换对象为 Json
在前面的 springmvc-servlet.xml 中已经配置好了使用 Fastjson
把对象自动映射为 Json:
Gradle 依赖
1
compile 'com.alibaba:fastjson:1.2.41'
-
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43<mvc:annotation-driven>
<mvc:message-converters>
<!-- StringHttpMessageConverter 编码为 UTF-8,防止乱码 -->
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="UTF-8"/>
<property name="supportedMediaTypes">
<list>
<bean class="org.springframework.http.MediaType">
<constructor-arg index="0" value="text"/>
<constructor-arg index="1" value="plain"/>
<constructor-arg index="2" value="UTF-8"/>
</bean>
<bean class="org.springframework.http.MediaType">
<constructor-arg index="0" value="*"/>
<constructor-arg index="1" value="*"/>
<constructor-arg index="2" value="UTF-8"/>
</bean>
</list>
</property>
</bean>
<!-- FastJson -->
<bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter4">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
</list>
</property>
<property name="fastJsonConfig">
<bean class="com.alibaba.fastjson.support.config.FastJsonConfig">
<property name="features">
<list>
<value>AllowArbitraryCommas</value>
<value>AllowUnQuotedFieldNames</value>
<value>DisableCircularReferenceDetect</value>
</list>
</property>
<property name="dateFormat" value="yyyy-MM-dd HH:mm:ss"/>
</bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven> 创建类 Result.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19package com.xtuer.bean;
public class Result {
private boolean success;
private String message;
private Object data;
public Result(boolean success, String message) {
this(success, message, null);
}
public Result(boolean success, String message, Object data) {
this.success = success;
this.message = message;
this.data = data;
}
// Getters and Setters
}Controller 里添加方法
1
2
3
4
5
public Result ajaxObject() {
return new Result(true, "你好");
}访问 http://localhost:8080/ajax-object
输出:
{"message":"你好","success":true}