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;
}
}
转载于:https://blog.51cto.com/sdqdwc/1830050