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测试:
Springmvc接受json参数总结_第1张图片
Springmvc接受json参数总结_第2张图片
这里要注意@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注解
Springmvc接受json参数总结_第3张图片
这时聪明的spring会帮我按照变量的名字自动注入,但是这是很容易遇到status=400

<html><body><h1>Whitelabel Error Pageh1><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 2018div><div>There was an unexpected error (type=Bad Request, status=400).div><div>Validation failed for object='user'. Error count: 1div>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

这是看看发送的参数:
Springmvc接受json参数总结_第4张图片
居然不是我拼装好的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){
Springmvc接受json参数总结_第5张图片
5,POST方法,后台需要得到一个List类型。

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

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

  @RequestMapping(value = "/insertValues", method = {RequestMethod.POST})
    public JsonResult insertHighlights(@RequestParam(name = "values[]",required = true) List 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){  
        
    }  
}); 

Springmvc接受json参数总结_第7张图片

你可能感兴趣的:(spring)