SpringMVC详解(六)------与json交互
Json(JavaScript Object Notation),它是一种轻量级数据交换格式,格式简单,易于读写,目前使用特别广泛。那么这篇博客我们主要谈谈在 SpringMVC 中,如何对 json 数据格式进行解析和转换?
本篇博客源码链接:http://pan.baidu.com/s/1kURnwDx 密码:b37t
1、两种交互模式
上图显示了客户端请求数据的两种格式,一种是 直接请求 json 数据,另一种是 key/value 数据。但是不管请求是哪种数据,为了在前端页面方便对结果进行解析。最终我们都转换为 json 数据格式。
2、导入相应的 jar 包(详情参看源码)
3、在 springmvc.xml 文件中配置 json 转换器
第一种方法:
1 | <mvc:annotation-driven ></mvc:annotation-driven> |
第二种方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <!-- 用于将对象转换为 JSON --> <bean id= "stringConverter" class = "org.springframework.http.converter.StringHttpMessageConverter" > <property name= "supportedMediaTypes" > <list> <value>text/plain;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.annotation.AnnotationMethodHandlerAdapter" > <property name= "messageConverters" > <list> <ref bean= "stringConverter" /> <ref bean= "jsonConverter" /> </list> </property> </bean> |
4、请求为 json 数据测试
这里我们需要注意两个注解:
@ResponseBody把后台pojo转换json对象,返回到页面。
@RequestBody接受前台json数据,把json数据自动封装pojo。
①、jsp 页面
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | <%@ page language= "java" contentType= "text/html; charset=UTF-8" pageEncoding= "UTF-8" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd" > <html> <head> <meta http-equiv= "Content-Type" content= "text/html; charset=UTF-8" > <title>SpringMVC和 json 交互</title> <script type= "text/javascript" src= "${pageContext.request.contextPath}/js/jquery-2.1.4.min.js" ></script> </head> <script type= "text/javascript" > var dataJson = { 'username' : 'Bob' , 'sex' : '男' }; function requestJson(){ $.ajax({ type: "POST" , url: "${pageContext.request.contextPath}/requestJson" , //指定数据格式为 json contentType: "application/json;charset=UTF-8" , data:JSON.stringify(dataJson), dataType: "json" , success:function(data){ console.log(data.username); console.log(data.sex); } }); } </script> <body> <button onclick= "requestJson()" value= "请求是json,返回json" >请求是json,返回json</button> </body> </html> |
②、Controller
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | package com.ys.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.ys.po.User; @Controller public class UserController { //请求为json,返回json @RequestMapping ( "/requestJson" ) //@RequestBody将请求信息的json串转成user对象 //@ResponseBody将user对象转成json输出 @ResponseBody public User requestJson( @RequestBody User user) throws Exception{ System.out.println(user); return user; //由于@ResponseBody注解,将user转成json格式返回 } } |
③、测试
我们访问上面的jsp页面,然后点击按钮,进入到 Controller
然后我们查看返回的数据:
5、请求为 key/value 数据测试
①、JSP 页面
②、Controller
1 2 3 4 5 6 7 8 | //请求为key/value,返回json @RequestMapping ( "/requestKeyValue" ) //@RequestBody将请求信息的json串转成user对象 @ResponseBody public User requestKeyValue(User user) throws Exception{ System.out.println(user); return user; } |
③、测试
然后返回数据:
6、遇到的问题
①、如下代码,由于我们使用 Ajax 提交,我们在 JSP 页面引入了jquery 文件,发现无论使用绝对路径还是相对路径,系统总是找不到这个文件?
1 | <script type= "text/javascript" src= "${pageContext.request.contextPath}/js/jquery-2.1.4.min.js" ></script> |
原因:因为你在web.xml 文件中,对于过滤器的配置是拦截所有请求。所以类似于*.js,或者*.css这样的文件也被拦截了,故访问不到。
解决办法:
第一种办法:我们可以使用上面配置的拦截器只拦截 *.do,或者*.action,而不是 “/”。那么SpringMVC容器将不会拦截*.js,*.css这样的文件。但是这种风格不支持 Restful,建议不采用。
第二种方法:在web.xml中配置拦截器的过滤请求
1 2 3 4 5 6 7 8 9 | <!--要写在DispatcherServlet的前面, 让 defaultServlet先拦截请求,这样请求就不会进入Spring了,我想性能是最好的吧。--> <servlet-mapping> <servlet-name> default </servlet-name> <url-pattern>*.css</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name> default </servlet-name> <url-pattern>*.js</url-pattern> </servlet-mapping> |
第三种方法:在spingmvc.xml 中配置对静态资源不过滤
1 2 3 | <!-- 配置静态文件过滤器 --> <mvc:resources location= "/WEB-INF/css/" mapping= "/css/**" /> <mvc:resources location= "/WEB-INF/js/" mapping= "/js/**" /> |
②、也是比较容易犯的错误 415
这个错误产生的原因有很多。我们需要一步一步的排查:
第一步:必须保证导入的 jackson相关的jar包是全的。
第二步:在springmvc.xml文件中的配置的json转换器一定不能缺少,如何配查看本篇博客的第三点
第三步:书写 Ajax 请求时。contentType:"application/json;charset=UTF-8",不要不写 contentType 这个属性
第四步:Ajax传给后台的不要直接传字符串,要转换成json,即 data:JSON.stringify(dataJson),
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构