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


  • 2019-12-11 16:04:15

    CSS中的 “var()” 和 “:root”

    var() var()函数可以代替元素中任何属性中的值的任何部分。var()函数不能作为属性名、选择器或者其他除了属性值之外的值。(这样做通常会产生无效的语法或者一个没有关联到变量的值。)

  • 2019-12-11 16:18:51

    npm发布vue组件

    开发之前先看看官网的 开发规范 我们开发的之后期望的结果是支持 import、require 或者直接使用 script 标签的形式引入,就像这样

  • 2019-12-11 16:21:00

    .vue文件 加scoped 样式不起作用

    在vue组件中,为了使样式私有化(模块化),不对全局造成污染,在style标签上添加scoped属性,以表示它只属于当下的模块。但是要慎用,因为在我们需要修改公共组件(第三方库或者项目中定制的组件)的样式的时候,scoped会造成很多困难,组要增加额外的复杂度。

  • 2019-12-11 16:22:04

    Vue中的scoped和scoped穿透,scoped原理

    在Vue文件中的style标签上有一个特殊的属性,scoped。当一个style标签拥有scoped属性时候,它的css样式只能用于当前的Vue组件,可以使组件的样式不相互污染。如果一个项目的所有style标签都加上了scoped属性,相当于实现了样式的模块化。

  • 2019-12-12 14:19:32

    laravel自定义分页LengthAwarePaginator

    有时候我们使用larave提供的后台分页数据库查询,有时候限制太多,我们需要自己定制分页功能。 下面是我给大家一个例子,我们可以根据例子,制作自己的分页功能。