SpringMVC中Json数据开发的方式

168 阅读1分钟
  • 添加 json 依赖 jar 包
  • 修改 servlet-context.xml,添加 json 转换器配置
  • 使用注解进行数据绑定@RequestBody @ResponseBody

案例实操

1.添加 json 依赖 jar 包

<!-- 添加 json 依赖 jar 包 --> 

<dependency> 

    <groupId>com.fasterxml.jackson.core</groupId> 

    <artifactId>jackson-core</artifactId> 

    <version>2.7.0</version> 

</dependency> 

<dependency> 

    <groupId>com.fasterxml.jackson.core</groupId> 

    <artifactId>jackson-databind</artifactId> 

    <version>2.7.0</version> 

</dependency>  

<dependency> 

    <groupId>com.fasterxml.jackson.core</groupId> 

    <artifactId>jackson-annotations</artifactId> 

    <version>2.7.0</version> 

</dependency> 

2.修改 servlet-context.xml

添加 json 转换器配置

<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"> 
</bean> 

<bean 
class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"> 

    <property name="messageConverters"> 

        <list> 

            <bean  class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" /> 

        </list> 

    </property> 

</bean> 

或者

<!-- mvc 请求映射 处理器与适配器配置 --> 

<mvc:annotation-driven> 

    <mvc:message-converters> 

        <bean  

        class="org.springframework.http.converter.StringHttpMessageConverter" /> 

        <bean 

        class="org.springframework.http.converter.json.MappingJackson2HttpMessageConver 

        ter" /> 

    </mvc:message-converters> 

</mvc:annotation-driven> 

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 页面定义

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 
<% 
String path = request.getContextPath(); 
String basePath =request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 
%> 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 

<html> 

    <head> 

        <base href="<%=basePath%>"> 

        <title>My JSP 'test.jsp' starting page</title> 

        <meta http-equiv="pragma" content="no-cache">

        <meta http-equiv="cache-control" content="no-cache">

        <meta http-equiv="expires" content="0">

        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

        <meta http-equiv="description" content="This is my page">

        <script type="text/javascript" src="js/jquery-1.7.2.js"></script>

   		<script type="text/javascript">

    	function 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); 

            	}  

            }) 

        } 

    </script>  

    </head>  

<body> 

	<input type="button" value="请求响应 json" onclick="test1()"/> 

	<input type="button" value="响应 json" onclick="test2()"/> 

</body> 

</html> 

扩展

@ResponseBody

该注解用于将 Controller 的方法返回的对象,通过适当的 HttpMessageConverter转换为指定格式后,写入到 Response 对象的 body 数据区。

返回的数据不是 html 标签的页面,而是其他某种格式的数据时(如 json、xml 等) 使用(通常用于 ajax 请求)

@RequestBody

该注解用于读取 Request 请求的 body 部分数据,使用系统默认配置的 HttpMessageConverter 进行解析,然后把相应的数据绑定到要返回的对象上 ,再把 HttpMessageConverter 返回的对象数据绑定到 controller 中方法的参数上

Json 数据使用好处

Json 在企业开发中已经作为通用的接口参数类型,在页面(客户端)解析很方便。

SpringMvc 对于 json 提供了良好的支持,这里需要修改相关配置,添加 json 数据支持功能