服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - 基于@GetMapping注解携带参数的方式

基于@GetMapping注解携带参数的方式

2022-12-02 17:39程序逸 Java教程

这篇文章主要介绍了基于@GetMapping注解携带参数的方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

@GetMapping注解携带参数方式

今天突然发现,当我们根据id查询用户信息时,如果不想通过localhost:8080//findOne?id=1来访问,而是通过localhost:8080//findOne/1这样的url来访问,结果找了一大圈都没有发现,现在来说明一下实现。

基于@GetMapping注解携带参数的方式

这里使用@PathVariable注解来注解参数,value中使用{参数名}来实现。

使用@GetMapping注解,用一个对象来接受参数报错400

controller 

?
1
2
3
4
@GetMapping("/products")
public ApiResult<List<YxStoreProductQueryVo>> goodsList(YxStoreProductQueryParam productQueryParam){
        return ApiResult.ok(storeProductService.getGoodsList(productQueryParam));
    }

接受参数的实体

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Data
@EqualsAndHashCode(callSuper = true)
@ApiModel(value="YxStoreProductQueryParam对象", description="商品表查询参数")
public class YxStoreProductQueryParam extends QueryParam {
    private static final long serialVersionUID = 1L;
    private int page;   
    private int limit;
    private int sid;
    private int cid;
    private int news;
    private String priceOrder;
    private String salesOrder;
    private String keyword;
    private Integer brandId;    
}

请求地址:

http://127.0.0.1:8008/api/products?page=&limit=8&keyword=&sid=129&news=0&priceOrder=&salesOrder=

后台打印报错信息:

Field error in object 'yxStoreProductQueryParam' on field 'page': rejected value []; codes [typeMismatch.yxStoreProductQueryParam.page,typeMismatch.page,typeMismatch.int,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [yxStoreProductQueryParam.page,page]; arguments []; default message [ page ]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'int' for property 'page'; nested exception is java.lang.NumberFormatException: For input string: ""]

解决办法(总结)

如果参数是int或者Integer类型的,要么就不传参数要么就要传递一个具体的数

错误方法:

http://127.0.0.1:8008/api/products?page=&limit=8&keyword=&sid=129&news=0&priceOrder=&salesOrder=

正确方法:

http://127.0.0.1:8008/api/products?limit=8&keyword=&sid=129&news=0&priceOrder=&salesOrder= 

以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/qq_43265564/article/details/117334172

延伸 · 阅读

精彩推荐