PostMapping,GetMapping访问多个路径,报错500解决

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

1:

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

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

2.

    @PostMapping(value = {"/queryCurWeatherNullById/{id}", "/queryCurWeatherNullById/{id}/{name}"})
    @Override
    public List 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,

如果某个参数不为空,则不必再定义required,默认为true

3.

    @PostMapping(value = {"/queryCurWeatherNullById/{id}", "/queryCurWeatherNullById/{id}/{name}"})
    @Override
    public List 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原始类型也可能会报错,所以数字类的参数类型最后都是引用类型

你可能感兴趣的:(Java,SpringMVC,SpringBoot)