Vue全家桶+SSR+Koa2全栈开发美团网(已完结)2018年(最全)

1. SpringMVC Json交互
  在 Java WEB 中经常用到 Json 数据来进行接口调用,传递数据,主要是因为 Json 格式的数据容易解析。SpringMVC支持 Json 格式的数据使用注解进行解析或转为 Json。

2. SpringMVC Json 交互相关注解
  @RequestBody :用于读取 HTTP 请求的内容(字符串),通过 SpringMVC 提供的 HttpMessageConverter 接口将读到的内容转换为 Json、XML 等格式的数据并绑定到 Controller 方法的参数上。
  @ResponseBody :用于将 Controller 的方法返回的对象,通过HttpMessageConverter 接口转换为指定格式的数据如:Json、XML 等格式,再通过 Response 响应给客户端。

3. 导入 Jackson JAR
  Jackson 1.X 的需要导入的 JAR 包是 jackson-core-xxx.jar 和jackson-mapping-xxx.jar;Jackson 2.X 的需要导入的 JAR 包是 jackson-core-xxx.jar 、 jackson-annotations-xxx.jar 和 jackson-databind-xxx.jar。我们这里用的是 Jackson 2.X,点击下载。


  这里我们导入 Jquery ,通过 Ajax 请求进行测试。注意,在 springmc.xml 中配置一下静态资源文件,最好这样,不然以后你的 DispatcherServlet 改变了拦截方式,js 就会被拦截,不能使用。

<!-- 对静态资源访问 -->
<mvc:resources location="/js/" mapping="/js/**"/>
1
2
  我这里使用的注解的处理器适配器是使用 mvc:annotation-driven,如果不是就需要配置才可以使用上述两个注解,配置有:

<!--注解适配器 -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
    <property name="messageConverters">
    <list>
        <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
    </list>
    </property>
</bean>

1
2
3
4
5
6
7
8
9
4. 请求 Json,返回 Json
  在 JSP 中 导入 Jquery 并编写代码。

<script type="text/javascript" src="<%=request.getContextPath() %>/js/jquery-3.3.1.js"></script>
1
<script type="text/javascript">

//请求json 响应json
function requestJson(){
    $.ajax({
        type:"post",
        url:"${pageContext.request.contextPath }/json/requestJson.action",
        contentType:"application/json;charset=utf-8",
        data:'{"name":"商品名称","price":99}',
        success:function(data){
            console.log(data);
        }
    });
}

</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
  Controller 中编写方法:

@RequestMapping("requestJson")
public @ResponseBody Items requestJson(@RequestBody Items items) {
    System.out.println(items);
    
    return items;
}
1
2
3
4
5
6
5. 请求 key/value,返回 Json
  在 JSP 中 导入 Jquery 并编写代码。

<script type="text/javascript">

//请求key/value 响应json
function responseJson(){
    $.ajax({
        type:"post",
        url:"${pageContext.request.contextPath }/json/responseJson.action",
        data:{
            "name":"商品名称",
            "price":99
        },
        success:function(data){
            console.log(data);
        }
    });
}
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
  Controller 中编写方法:

@RequestMapping("responseJson")
public @ResponseBody Items responseJson(Items items) {
    
    return items;
}
1
2
3
4
5
6. 统一测试
  JSP 添加代码:

<body>
    <button onclick="requestJson()">requestJson</button>
    <hr>
    <button onclick="responseJson()">responseJson</button>
</body>
1
2
3
4
5
  J点击相应的按钮,按 F12 在控制台打印如下内容:

--------------------- 
作者:lytao123 
来源:CSDN 
原文:https://blog.csdn.net/qq_24598601/article/details/85028428 
版权声明:本文为博主原创文章,转载请附上博文链接!

猜你喜欢

转载自blog.csdn.net/weixin_44226873/article/details/85532556