PostMapping,GetMapping不固定路径的写法

2019-10-23 23:25:22


PostMapping中的value属性是数组,所以可以定义多个路径,required属性默认是true,不必再写required=true,默认表示该参数是必须要有的,如果写required=false,表示该参数是可选的,可有可无。

    @PostMapping("/queryCurWeatherNullById/{id}/{name}")
    @Override
    public List<WeatherPO> queryCurWeatherNullById(@PathVariable("id") Long id,
                                                   @PathVariable("name") String name) {

如上所示,如果路径是/queryCurWeatherNullById/1/str正确,但是如果是/queryCurWeatherNullById/queryCurWeatherNullById/1则报错404 NOT FOUND.原因是id,name属性默认是必须要有的。

    @PostMapping(value = {"/queryCurWeatherNullById/{id}", "/queryCurWeatherNullById/{id}/{name}"})
    @Override
    public List<WeatherPO> queryCurWeatherNullById(@PathVariable(value = "id") Long id,
                                                   @PathVariable(value = "name", required = false) String name) {

如上所示,如果路径是http://localhost:8080/weather/queryCurWeatherNullById/1/str正确,是http://localhost:8080/weather/queryCurWeatherNullById/1正确,但是如果是http://localhost:8080/weather/queryCurWeatherNullById则报错404 NOT FOUND.原因是id属性默认是必须要有的。


所以如果某个参数可能为空,则需要定义required=false,


    @PostMapping(value = {"/queryCurWeatherNullById/{id}", "/queryCurWeatherNullById/{id}/{name}"})
    @Override
    public List<WeatherPO> queryCurWeatherNullById(@PathVariable(value = "id", required = false) int id,
                                                   @PathVariable(value = "name", required = false) String name) {


关于报错500,此时id是可选的,当路径中不含有id时,则报错如下:


java.lang.IllegalStateException: Optional int parameter 'id' is present but cannot be translated into a null value due to being declared as a primitive type. Consider declaring it as object wrapper for the corresponding primitive type.

    at org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver.handleNullValue(AbstractNamedValueMethodArgumentResolver.java:238)

    at org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver.resolveArgument(AbstractNamedValueMethodArgumentResolver.java:111)


原因是int类型不能为null,id的类型是int,但是Integer可以为null,把id修改为Integer类型即可。(这个错误很隐蔽!!!!)


当然如果是long,float,double原始类型也可能会报错,所以数字类的参数类型最后都是引用类型


  • 2017-03-27 16:24:26

    laravel,gulp,Browsersync浏览器同步测试

    Browsersync能让浏览器实时、快速响应您的文件更改(html、js、css、sass、less等)并自动刷新页面。更重要的是 Browsersync可以同时在PC、平板、手机等设备下进项调试。您可以想象一下:“假设您的桌子上有pc、ipad、iphone、android等设备,同时打开了您需要调试的页面,当您使用browsersync后,您的任何一次代码保存,以上的设备都会同时显示您的改动”。无论您是前端还是后端工程师,使用它将提高您30%的工作效率。

  • 2017-03-28 09:27:41

    Java中Arrays的asList()方法

    Java中Arrays的asList()方法 可以将 数组转为List 但是,这个数组类型必须是 引用类型的,如果是8中基本数据类型就不可以 原因如下,引用别人的一篇文章:

  • 2017-03-28 10:58:01

    No such property: sonatypeRepo for class:

    这种问题一般是出现在导入一些开源项目的时候。原因为该项目的原作者会把项目发布到maven中央仓库中,所以在gradle中添加了相关的maven发布任务,而发布任务需要配置