Springmvc接受json参数总结

关于springmvc的参数我觉得是个头痛的问题,特别是在测试的时候,必须要正确的注解和正确的content-type 后端才能被正确的请求到,否则可能报出400,415等等bad request。注意在主流浏览器中只要不指定,默认的Content-type是
1,最简单的GET方法,参数在url里面,比如:
@RequestMapping(value = “/artists/{artistId}”, method = {RequestMethod.GET})
@PathVariable去得到url中的参数。

public Artist getArtistById(@PathVariable String artistId)

2,GET方法,参数接在url后面。

@RequestMapping(value = "/artists", method = {RequestMethod.GET})
  public ResponseVO getAllArtistName(
                         @RequestParam(name = "tagId", required = false) final String tagId) 

访问的时候/artists?tagId=1
@RequestParam相当于request.getParameter("")
3,POST方法,后端想得到一个自动注入的对象

@RequestMapping(value = "/addUser", method = {RequestMethod.POST})
    public void addUser(@RequestBody UserPO users){

用restlet_client测试:
这里写图片描述
这里写图片描述
这里要注意@RequestBody,它是用来处理前台定义发来的数据Content-Type: 不是application/x-www-form-urlencoded编码的内容,例如application/json, application/xml等;我们使用@RequestBody注解的时候,前台的Content-Type必须要改为application/json,如果没有更改,前台会报错415(Unsupported Media Type)。后台日志就会报错Content type ‘application/x-www-form-urlencoded;charset=UTF-8’ not supported

如果是表单提交 Contenttype 会是application/x-www-form-urlencoded,可以去掉@RequestBody注解
这里写图片描述
这时聪明的spring会帮我按照变量的名字自动注入,但是这是很容易遇到status=400

<html><body><h1>Whitelabel Error Page</h1><p>This application has no explicit mapping for /error, so you are seeing this as a fallback.</p><div id='created'>Tue Feb 06 16:49:34 GMT+08:00 2018</div><div>There was an unexpected error (type=Bad Request, status=400).</div><div>Validation failed for object=&#39;user&#39;. Error count: 1</div></body></html>

这是springboot的报错,原因是bean中有不能注入的变量,因为类型的不一样,一般是date和int的变量,所以在使用的时候要特别注意。

**如果前端使用的$.ajax来发请求,希望注入一个bean。**这时又有坑了,代码如下:

$.ajax({
				headers: {
					Accept: "application/json; charset=utf-8"
				},
				method : 'POST',
				url: "http://localhost:8081/user/saveUser",
				contentType: 'application/json',
				dataType:"json",
				data: json,
				//async: false, //true:异步,false:同步
				//contentType: false,
				//processData: false,
				success: function (data) {
					if(data.code == "000000"){
						alert(data.desc);
						window.location.href="http://localhost:8081/login.html";
					}
				},
				error: function (err) {
					alert("error");

				}});

马上就报错了:
error
:
“Bad Request”
exception
:
“org.springframework.http.converter.HttpMessageNotReadableException”
message
:
“JSON parse error: Unrecognized token ‘name’: was expecting ‘null’, ‘true’, ‘false’ or NaN; nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token ‘name’: was expecting ‘null’, ‘true’, ‘false’ or NaN↵ at [Source: java.io.PushbackInputStream@7fc056ba; line: 1, column: 6]”
path
:
“/user/saveUser”
status
:
400
timestamp
:
1518094430114

这是看看发送的参数:
这里写图片描述
居然不是我拼装好的json,
data: json, 改成 data: JSON.stringify(json),后端接收json String,json只是个对象,所以解析不了!

4,POST方法,需要得到一个List的类型
@RequestMapping(value = “/addUser”, method = {RequestMethod.POST})
public void addUser(@RequestBody List users){
这里写图片描述
5,POST方法,后台需要得到一个List类型。

方式一:
@RequestMapping(value = "/getPlayURL", method = {RequestMethod.POST})
    @ResponseBody
    public List<Song> getPlayUrlBySongIds(
            @RequestParam(name = "songId",required = false) List<String> songIdList) {

这样去发ajax请求就是可以的
$.post(“http://music/getPlayURL”,{
songId:“1108377224,1000027609”
},
但是我在restlet_client 发送json数据测试后台就拿不到参数。真的奇怪
这里写图片描述
方式二:

  @RequestMapping(value = "/insertValues", method = {RequestMethod.POST})
    public JsonResult insertHighlights(@RequestParam(name = "values[]",required = true) List<String> values,
                                       @RequestParam(name = "type", required = true) String type) throws BizException {
        monthlyReportService.insertValues(values, type);

        return new JsonResult(StatusCode.OK);
    }

js代码:

var allFilePaths = new Array();
for (var i = 0; i < 3; i++) {
    allFilePaths.push("test String");
}
$.ajax({  
    type: "POST",  
    url: "http://127.0.0.1:8080/insertValues",  
    dataType: 'json',  
    data: {"values":allFilePaths,"type":"edw"},  
    success: function(data){  
         
    },  
    error: function(res){  
        
    }  
}); 

在这里插入图片描述

<think>好的,我现在需要帮助用户理解SpringMVC如何处理XML和JSON参数的接收与返回。首先,我得回忆一下SpringMVC的工作原理,特别是关于消息转换的部分。用户提到了接收和返回两种数据格式,所以需要分两部分来解答:参数接收和响应返回。 根据用户提供的引用,特别是引用[1]和[2],接收XML和JSON参数涉及到请求体的解析。我记得SpringMVC使用HttpMessageConverter来处理不同的媒体类型。当客户端发送请求时,Content-Type头部指定了媒体类型,比如application/xml或application/json,Spring会根据这个类型选择合适的转换器来解析请求体到方法参数中。比如,使用@RequestBody注解的参数会触发相应的转换器。 对于XML,可能需要像JAXB这样的库来将XML数据绑定到Java对象,而JSON处理通常使用Jackson库。用户提到的引用[1]中实验了接收XML参数,这需要配置相关的依赖,比如JAXB或Jackson的XML模块。同样,引用[2]讨论了接收JSON参数的情况,需要确保Jackson库在类路径中,这样Spring会自动配置MappingJackson2HttpMessageConverter。 在返回XML或JSON响应方面,引用[3]和[4]提到使用@ResponseBody或@RestController注解,这会告诉Spring使用HttpMessageConverter将返回的对象转换为指定的格式。响应格式由Accept头部决定,或者可以通过produces属性强制指定。例如,如果控制器方法设置了produces = MediaType.APPLICATION_JSON_VALUE,Spring会优先返回JSON,前提是客户端接受该类型。 需要确认是否依赖正确配置。比如,处理XML需要添加Jackson XML模块或JAXB依赖,JSON需要Jackson的依赖。同时,检查是否启用了注解驱动,即<mvc:annotation-driven>或使用@EnableWebMvc,这会自动注册默认的转换器。 用户可能还想知道如何同时支持多种格式,这时候内容协商机制就起作用了。Spring会根据请求的Accept头部和可用的转换器来决定响应格式。如果同时配置了Jackson和JAXB,Spring可以自动处理XML和JSON的转换。 总结起来,处理流程大致是:客户端发送请求时指定Content-Type和Accept头部,Spring选择对应的HttpMessageConverter来解析请求体和生成响应。开发人员需要正确配置依赖和注解,如@RequestBody和@ResponseBody,以确保数据正确转换。 可能的相关问题包括如何配置多个数据格式、处理不同版本的API内容协商,或者解决常见的转换错误。需要确保回答覆盖这些方面,并引用提供的资料来支持解释。</think>### SpringMVC接收XML/JSON参数及返回原理分步解析 #### 一、接收XML/JSON参数 1. **HTTP请求头声明格式** - XML请求需设置:`Content-Type: application/xml` - JSON请求需设置:`Content-Type: application/json` - SpringMVC通过`HttpMessageConverter`接口实现自动解析[^2] 2. **控制器参数绑定** ```java @PostMapping("/api") public Response handleRequest(@RequestBody UserDTO user) { // 使用@RequestBody注解触发消息转换 } ``` - XML解析依赖`JAXB`或`Jackson XML`库,需添加依赖: ```xml <dependency> <groupId>com.fasterxml.jackson.dataformat</groupId> </artifactId>jackson-dataformat-xml</artifactId> </dependency> ``` - JSON解析需`Jackson`库(Spring Boot默认包含) 3. **转换器工作流程 $$ \text{HTTP Request} \xrightarrow[\text{识别}]{\text{Content-Type}} \text{对应MessageConverter} \xrightarrow{\text{反序列化}} \text{Java对象} $$ #### 二、返回XML/JSON响应 1. **响应格式控制** - 客户端通过`Accept`头指定格式:`application/xml` 或 `application/json` - 强制指定格式: ```java @GetMapping(value = "/data", produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public User getData() { return userService.findUser(); } ``` 2. **返回值处理机制 - 使用`@ResponseBody`或`@RestController`注解 - 根据`produces`设置或`Accept`头选择`HttpMessageConverter` - 默认优先级:Jackson JSON > Jackson XML > JAXB[^3] 3. **核心配置验证 ```xml <!-- 必须启用注解驱动 --> <mvc:annotation-driven> <mvc:message-converters> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/> <bean class="org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter"/> </mvc:message-converters> </mvc:annotation-driven> ``` #### 三、关键依赖清单 | 数据格式 | 必需依赖 | |----------|-----------------------------------| | JSON | spring-web, jackson-databind | | XML | jackson-dataformat-xml 或 JAXB |
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值