Spring请求路径带参数URL使用注解的写法

调用外部平台http接口,Post请求,url 为路径带有参数的形式:

http://xxxxxx.com/openApi/auth/getUserAuth?version=v1.0

使用 Retrofit 框架(本文使用的2.6.2版本)发送Post请求,可以在 @Post 注解中直接带上参数,如下:

    @POST("auth/getUserAuth?version=v1.0")
    Call<McgjResponse<UserAuthResponseDTO>> getUserAuth(@Body UserAuthRequest userAuthRequest);

       因为初次使用 Retrofit 框架,所以自己启动Spring服务模拟外部平台接口,发现之前一直都在@PostMapping中定义路径,还没怎么写过带参数的,导致写错了,报 404错误,记录一下下。先说正确写法:

正确写法:

@PostMapping(value ="/authorize/addRecord",params = "version=v1.0")
    public McgjResponse<UserAuthResponseDTO> test(){

其实@RequestMapping、@GetMapping、@PostMapping 三个注解都可以指定请求Header、请求path、以及请求params。

@RequestMapping("/foo")   等价于 @RequestMapping(path="/foo")

	/**
	 * The primary mapping expressed by this annotation.
	 * <p>In a Servlet environment this is an alias for {@link #path}.
	 * For example {@code @RequestMapping("/foo")} is equivalent to
	 * {@code @RequestMapping(path="/foo")}.
	 * <p>In a Portlet environment this is the mapped portlet modes
	 * (i.e. "EDIT", "VIEW", "HELP" or any custom modes).
	 * <p><b>Supported at the type level as well as at the method level!</b>
	 * When used at the type level, all method-level mappings inherit
	 * this primary mapping, narrowing it for a specific handler method.
	 */
	@AliasFor("path")
	String[] value() default {};

所以平常在括号中直接写,只是指定了 path。如果错误地把参数写到请求 path 中,则会报 HTTP 404 错误,如下错误写法:

错误写法:

//错误写法
@PostMapping(value ="/auth/getUserAuth?version=v1.0")
    public McgjResponse<UserAuthResponseDTO> test(){

总结:这三个注解平时用的是如此之多,却如此不熟悉,实在不应该!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值