一、使用HttpServletResponse来处理-不需要配置解析器
@RequestMapping(value = "/ajax", method=RequestMethod.POST)
public void ajax(String name, HttpServletResponse response) throws IOException {
if("siggy".equals(name)) {
response.getWriter().print("true");
}
else {
response.getWriter().print("false");
}
}
<script src="./jquery/jquery-3.2.1.min.js"></script>
<script>
$(document).ready(function() {
$("button").click(function() {
$.post("ajax.do", {'name':$("#txtName").val()}, function(data) {
alert("数据:" + data);
});
});
});
</script>
</head>
<body>
用户名:<input id="txtName" type="text" /><br><br>
<button>向页面发送 HTTP POST 请求,然后获得返回的结果</button><br><br>
</body>
./ |
|
/ |
|
二、Spring MVC处理JSON数据(用异步响应回去的一般都是JSON格式的数据)
- 导入jar包:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.7</version>
</dependency>
- 配置JSON转换器:
<!-- json配置 -->
<!-- 用于将对象转换为 JSON -->
<bean id="stringConverter"
class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/plain;charset=UTF-8</value>
</list>
</property>
</bean>
<bean id="jsonConverter"
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean>
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="stringConverter" />
<ref bean="jsonConverter" />
</list>
</property>
</bean>
- Controller代码:
@Controller
publicclass
JsonController {
@RequestMapping(value ="/json")
@ResponseBody
publicList<User> json() {
List<User>list
=
newArrayList<User>();
list.add(newUser(1,
"zhangsan",
"男"));
list.add(newUser(2,
"nico",
"female"));
list.add(newUser(3,
"jackson",
"男"));
returnlist;
}
}
JSP页面代码
|
<scriptsrc="./jquery/jquery-3.2.1.min.js"></script>
<script>
$(document).ready(function()
{
$("#button").click(function()
{
$.post("json.do",function(data)
{
varhtml
= "";
for(vari
= 0; i < data.length; ++i) {
html +="<tr><td>"+data[i].id
+"</td><td>"+data[i].name
+"</td><td>"+data[i].sex+"</td></tr>";
}
$("#content").html(html);
});
});
});
</script>
</head>
<body>
<inputid="button"type="button"value="获取数据"/><br>
<tablewidth="80%"align="center">
<tr>
<td>编号</td>
<td>姓名</td>
<td>性别</td>
</tr>
<tbodyid="content">
</tbody>
</table>
</body>
|
实体类代码
|
publicclass
User {
privateint
id;
privateString
name;
privateString
sex;
publicUser() {
}
publicUser(intid,
Stringname, Stringsex) {
super();
this.id=
id;
this.name=
name;
this.sex=
sex;
}
//下面省略get、set方法
|