好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

亲测SpringBoot参数传递及@RequestBody注解---踩过的坑及解决

SpringBoot 参数传递及@RequestBody注解注意点

前台正确的js书写格式是

?

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

//点击查询, 执行下面这个函数

$( "#searchByCriteria" ).click( function () {

      //var paramdata = $("#bck_qry_criteria_form").serializeJson();//serializeJson()是自定义的form 格式化为json函数

      var paramdata = {

          type:$( "#bck_type" ).val(),

          title:$( "#bck_title" ).val(),

          start:$( "#bck_start" ).val(),

          end:$( "#bck_end" ).val()

      };

      paramdata = JSON.stringify(paramdata);

      $.ajax({

          type: "post" ,

          data: paramdata,

          url: "/getNews" ,

          cache: false ,

          headers : { "Content-Type" : "application/json;charset=utf-8" },

          success: function (data) {

              var code = data.code;

              var t = data.t;

              if (code == 200){alert(JSON.stringify( "提交成功! 我们会尽快联系您!" ));}

              if (code == 500){alert(JSON.stringify(t));}

              //$("#input_phone").val("");//清空输入框

          }

      })

  });

上面中传递的参数一定要用JSON.stringify(paramdata); 方法将参数转换成json格式的字符串; 因为SpringBoot 中@RequestBody注解要求的必须是json格式的字符串才能注入参数, 第二就是大坑, 大坑, 大坑, 请求中必须 带上请求头,不然会报下面错误

org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported

后台正确的Controller书写格式是

其中consumes = [application/json], 规范的讲是要加的, 它规范了,前台要传递json格式的参数. 但是如果你不加也是可以的, 亲测不加也能封装到参数.NewsParamsMap中属性

?

1

2

3

4

5

6

@PostMapping (value = "/getNews" ,  consumes = "application/json" )

@ResponseBody

public PageInfo<NewsList> getNewsList( @RequestBody NewsParamsMap map){

     System.out.println( "这是正确的用法" );

     return null ;

}

NewsParamsMap 中有Integer 有Date, 前台传过来都是字符串, springboot,会根据名称一一对应, 将数据转换成相应的类型.

?

1

2

3

4

5

6

7

8

9

public class NewsParamsMap {

     private Integer type;

     private String title;

     private Date start;

     private Date end;

    ...

    set get 方法

    ...

}

RequestBody 作为参数使用

最近在接收一个要离职同事的工作,接手的项目是用SpringBoot搭建的,其中看到了这样的写法:

在CODE上查看代码片 派生到我的代码片

?

1

2

3

4

5

6

@RequestMapping ( "doThis" ) 

public String doThis(HttpServletRequest request, 

         @RequestParam ( "id" ) Long id, // 用户ID 

         @RequestParam ( "back_url" ) String back_url, // 回调地址          

         @RequestBody TestEntity json_data // json数据,对于java实体类 

){ //...

这个是一个请求映射方法,然后用浏览器输入url:

http://127.0.0.1:8080/test/doThis?id=1&back_url=url&json_data={"code":2,"message":"test"}

在这个方法中,使用@RequestParam获取参数,然后使用@RequestBody对json格式的参数转换为Java类型

在运行的时候发现报错:Required request body is missing

@RequestBody的使用需要加载MappingJackson2HttpMessageConverter,但是SpringBoot的官方文档提到,这个是默认已经加载的了,而且json字符串和javabean也没有书写的错误

因此考虑到应该是请求Content-Type的问题,因为使用浏览器输入url的方式没有办法定义Content-Type,因此spring无法发现request body

为了证实这个想法,自己书写一个请求类

在CODE上查看代码片 派生到我的代码片

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

String add_url = "http://127.0.0.1:8080/test/doThis" ; 

    URL url = new URL(add_url); 

    HttpURLConnection connection = (HttpURLConnection)url.openConnection(); 

    connection.setDoInput( true ); 

    connection.setDoOutput( true ); 

    connection.setRequestMethod( "POST" ); 

    connection.setUseCaches( false ); 

    connection.setInstanceFollowRedirects( true ); 

    connection.setRequestProperty( "Content-Type" , "application/json" ); 

    connection.connect(); 

    DataOutputStream out = new DataOutputStream(connection.getOutputStream()); 

    JSONObject obj = new JSONObject(); 

      

    obj.put( "code" , - 1002 );      

    obj.put( "message" , "msg" ); 

    out.writeBytes(obj.toString()); 

    out.flush(); 

    out.close();

请求还是失败,经过调试,发现需要去掉所有的@RequestParam注解才能成功

小结一下

1、@RequestBody需要把所有请求参数作为json解析,因此,不能包含key=value这样的写法在请求url中,所有的请求参数都是一个json

2、直接通过浏览器输入url时,@RequestBody获取不到json对象,需要用java编程或者基于ajax的方法请求,将Content-Type设置为application/json

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

原文链接:https://blog.csdn.net/fengzyf/article/details/83549830

查看更多关于亲测SpringBoot参数传递及@RequestBody注解---踩过的坑及解决的详细内容...

  阅读:38次