SpringMVC中Json数据开发的方式添加 json 依赖 jar 包
修改 servlet-context.xml,添加 json 转换器配置
使用注解进行数据绑定@RequestBody @ResponseBody
案例实操
1.添加 json 依赖 jar 包
com.fasterxml.jackson.core
jackson-core
2.7.0
com.fasterxml.jackson.core
jackson-databind
2.7.0
com.fasterxml.jackson.core
jackson-annotations
2.7.0
2.修改 servlet-context.xml
添加 json 转换器配置
class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
或者
class="org.springframework.http.converter.StringHttpMessageConverter" />
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConver
ter" />
3.Json 数据绑定的支持
@Controller
@RequestMapping("/user")
public class UserLoginController {
@RequestMapping("/addUser")
@ResponseBody
public User addUser(@RequestBody User user){
System.out.println(user);
return user;
}
@RequestMapping("/getUser")
@ResponseBody
public User getUser(User user){
System.out.println(user);
return user;
}
}
Jsp 页面定义
String path = request.getContextPath();
String basePath =request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
My JSP 'test.jsp' starting pagefunction test1(){
$.ajax({
type:"post",
url:"user/addUser.do",
dataType:"json",
contentType:"application/json;charset=utf-8",
data:'{"userName":"xxx","userPwd":"123456"}',
success:function(data){
alert(data.userName+"--"+data.userPwd);
}
})
}
function test2(){
$.ajax({
type:"post",
url:"user/getUser.do",
data:"userName=xxx&userPwd=123456",
dataType:"json",
success:function(data){
alert(data.userName+"--"+data.userPwd);
}
})
}
扩展
@ResponseBody
该注解用于将 Controller 的方法返回的对象,通过适当的 HttpMessageConverter转换为指定格式后,写入到 Response 对象的 body 数据区。
返回的数据不是 html 标签的页面,而是其他某种格式的数据时(如 json、xml 等) 使用(通常用于 ajax 请求)
@RequestBody
该注解用于读取 Request 请求的 body 部分数据,使用系统默认配置的 HttpMessageConverter 进行解析,然后把相应的数据绑定到要返回的对象上 ,再把 HttpMessageConverter 返回的对象数据绑定到 controller 中方法的参数上
Json 数据使用好处
Json 在企业开发中已经作为通用的接口参数类型,在页面(客户端)解析很方便。
SpringMvc 对于 json 提供了良好的支持,这里需要修改相关配置,添加 json 数据支持功能