首页 > 编程技术 > java

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

发布时间:2021-8-16 16:00

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(){

小结:

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

Spring注解@RequestMapping请求路径映射问题

@RequestMapping请求路径映射,如果标注在某个controller的类级别上,则表明访问此类路径下的方法都要加上其配置的路径;最常用是标注在方法上,表明哪个具体的方法来接受处理某次请求。

以下两种方式都可以从url中传参数,但是第二种方式的适用性更高一些,当参数中包含中文的时候,如果用第一种方式传参数,经常会出现参数还没到controller就已经经过编码了(例如:经过utf-8编码后,原本要传的参数就会以%+ab...cd这样的方式出现),然后controller接受到这样的请求后,根本无法解析该请求应该走那个业务方法。

然后就会出现常见的404问题。。。

package com.test.jeofey.web; 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping; 
 
@Controller
@RequestMapping("/path")
public class TestController {
 
 // 第一种传参数的方式 访问地址例如:http:域名/path/method1/keyWord.html
 @RequestMapping("method1/{keyWord}")
 public String getZhiShiDetailData(@PathVariable("keyWord") String keyWord,
   HttpServletRequest request, HttpServletResponse response){
  System.out.println(keyWord);
  return "v1/detail";
 }
 
 // 第二种传参数的方式 访问地址例如:http:域名/path/method2.html?key=keyWord
 @RequestMapping("method2")
 public String getCommonData(HttpServletRequest request, 
   HttpServletResponse response){
  String keyWord= request.getParameter("key");
  System.out.println(keyWord);
  return "v1/common";
 }  
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持猪先飞。

标签:[!--infotagslink--]

您可能感兴趣的文章: