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原始类型也可能会报错,所以数字类的参数类型最后都是引用类型


  • 2018-07-02 11:58:18

    探究Laravel使用env函数读取环境变量为null的问题

    最近在工作中遇到一个问题,不知道大家有没有遇到过,在 Laravel中(除 app/config 目录下的配置文件中)使用env函数读取环境变量,有时有用,有时返回 null,这究竟怎么回事?下面通过这篇文章让我们一探究竟。有需要的朋友们下面来一起看看吧。

  • 2018-07-10 16:56:00

    MUI-图片轮播控件

    图片轮播继承自slide插件,因此其DOM结构、事件均和slide插件相同; 在MUI框架中针对图片的轮播做了一个简单的封装。

  • 2018-07-10 16:56:42

    mysql in 排序 也可以按in里面的顺序来排序

    SQL: select * from table where id IN (3,6,9,1,2,5,8,7); 这样的情况取出来后,其实,id还是按1,2,3,4,5,6,7,8,9,排序的,但如果我们真要按IN里面的顺序排序怎么办?SQL能不能完成?是否需要取回来后再foreach一下?