• @RequestParam 和 @RequestBody 接受的时间格式


    这两个接受的时间格式不相同

    首先看一下他们的区别

    @RequestParam
    用来处理Content-Type: 为 application/x-www-form-urlencoded编码的内容。(Http协议中,如果不指定Content-Type,则默认传递的参数就是application/x-www-form-urlencoded类型)

    RequestParam可以接受简单类型的属性,也可以接受对象类型。
    实质是将Request.getParameter() 中的Key-Value参数Map利用Spring的转化机制ConversionService配置,转化成参数接收对象或字段。

    tip
    在Content-Type: application/x-www-form-urlencoded的请求中,
    get 方式中queryString的值,和post方式中 body data的值都会被Servlet接受到并转化到Request.getParameter()参数集中,所以@RequestParam可以获取的到。

    @RequestBody
    处理HttpEntity传递过来的数据,一般用来处理非Content-Type: application/x-www-form-urlencoded编码格式的数据。

    GET请求中,因为没有HttpEntity,所以@RequestBody并不适用。
    POST请求中,通过HttpEntity传递的参数,必须要在请求头中声明数据的类型Content-Type,SpringMVC通过使用HandlerAdapter 配置的HttpMessageConverters来解析HttpEntity中的数据,然后绑定到相应的bean上。
    总结
    在GET请求中,不能使用@RequestBody。
    在POST请求,可以使用@RequestBody和@RequestParam,但是如果使用@RequestBody,对于参数转化的配置必须统一。
    举个例子,在SpringMVC配置了HttpMessageConverters处理栈中,指定json转化的格式,如Date转成‘yyyy-MM-dd’,则参数接收对象包含的字段如果是Date类型,就只能让客户端传递年月日的格式,不能传时分秒。因为不同的接口,它的参数可能对时间参数有不同的格式要求,所以这样做会让客户端调用同事对参数的格式有点困惑,所以说扩展性不高。

    如果使用@RequestParam来接受参数,可以在接受参数的model中设置@DateFormat指定所需要接受时间参数的格式。

    另外,使用@RequestBody接受的参数是不会被Servlet转化统一放在request对象的Param参数集中,@RequestParam是可以的。

    综上所述,一般情况下,推荐使用@RequestParam注解来接受Http请求参数。

    @RequestParam中使用的时候:

      @PostMapping("/userVipInfoUpdate2")
        public Map<String, Object> updateUserInfo(@RequestParam int id,
                                                  @RequestParam int vip,
                                                  @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime time) {
            User user = UserFactory.newVipInfoInstance(id, vip, time); 
            userService.modifyVipInfo(user);
            return new OKReturnMap("修改用户信息成功!").getMap();
        }

    此时发送的数据格式应该是:

    {
        "id":81,
        "vip":2,
        "time":"2017-02-12T12:00:00"
    }

    在使用@RequestBody时,根据实体类的数据类型进行对应

       @PostMapping("/userVipInfoUpdate")
        public Map<String, Object> updateUserVipInfo(@RequestBody User user) {
            userService.modifyVipInfo(user);
            return new OKReturnMap("修改用户信息成功!").getMap();
        }
  • 相关阅读:
    Coding styles, code review
    Some links haven't take a look(C++, JS, IE9)
    前端学习,找到一下一些问题的答案
    Browser judgement
    Theme of Google
    Browser Time Line
    迷茫在10点左右……
    WebPageTest 检测web站点性能网站测试工具
    Invoke IFrame/window in cross domain in IE&FF notes
    [解决]多线程中出现由于代码已经过优化或者本机框架位于调用堆栈之上,无法计算表达
  • 原文地址:https://www.cnblogs.com/NCL--/p/10045102.html
Copyright © 2020-2023  润新知