您的位置:首页 > 编程语言 > Java开发

SpringMVC中Ajax、json的处理

2016-07-26 11:49 453 查看
1、HttpServletResponse来处理----不需要配置解析器
index.jsp
<html>
<head>
<title>My JSP 'index.jsp' starting page</title>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$("#txtname").blur(function(){
$.post("ajax.do",{'name':$("#txtname").val()},function(data){
alert(data);
});
});
});
</script>
</head>
<body>
用户名:<input type="text" id="txtname"/>
</body>
</html>
AjaxController
@RequestMapping("/ajax")
public void ajax(String name, HttpServletResponse resp) throws IOException{
if("siggy".equals(name)){
resp.getWriter().print(true);
}
else{
resp.getWriter().print(false);
}
}
2、SpringMVC处理json数据

a)导入JAR包
jackson-annotations-2.5.3.jar
jackson-core-2.5.3.jar
jackson-databind-2.5.3.jar
b)配置json转换器
<!-- 用于将对象转换为JSON -->
<bean id="stringConverter"
class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html; charset=UTF-8</value>
<value>application/json;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.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="stringConverter" />
<ref bean="jsonConverter" />
</list>
</property>
</bean>
b)controller代码
package com.wc.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wc.vo.User;

@Controller
public class JsonController {

@RequestMapping("/json")
@ResponseBody
public List<User> json(){
List<User> list = new ArrayList<User>();
list.add(new User(1,"zhangsan","男"));
list.add(new User(2,"nico","female"));
list.add(new User(3,"jackson","男"));
return list;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: