Spring Rest中如何同时使用@Pathvariable和@RequestParam

How to use @Pathvariable and @RequestParam at the same time in Spring Rest

我正在尝试在 spring-boot 中提供休息服务以匹配这样的请求:

http://localhost:8080/customer/v1/user/1/purchase?productId=2

所以,我创建了这样的服务:

@GetMapping(value = "/customer/v1/user/{userId}/purchase?productId={productId}")
public ResponseDto Test(@PathVariable("userId") String userId,@RequestParam("productId") String productId ){
    return  new ResponseDto();
}

但它似乎与请求不匹配,我收到此错误:

DispatcherServlet with name 'dispatcherServlet' processing GET request for [/customer/v1/user/1/purchase]
Looking up handler method for path /customer/v1/user/1/purchase
Did not find handler method for [/customer/v1/user/1/purchase]
Matching patterns for request [/customer/v1/user/1/purchase] are [/**]
URI Template variables for request [/customer/v1/user/1/purchase] are {}
Mapping [/customer/v1/user/1/purchase] to HandlerExecutionChain with handler [ResourceHttpRequestHandler [locations=[class path resource [META-INF/resources/], class path resource [resources/], class path resource [static/], class path resource [public/], ServletContext resource [/]],
Last-Modified value for [/customer/v1/user/1/purchase] is: -1
Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapter completed request handling
Successfully completed request
DispatcherServlet with name 'dispatcherServlet' processing GET request for [/error]
Looking up handler method for path /error
Returning handler method [public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest)]
Last-Modified value for [/error] is: -1
Written [{timestamp=Mon Oct 29 17:52:20 IRST 2018, status=404, error=Not Found, message=No message available, path=/customer/v1/user/1/purchase}] as "application/json" using [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@bb8ead8]
Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapter completed request handling
Successfully completed request

我尝试了不同的方法,包括在控制器级别使用@RequestParam,但仍然没有成功。

它抱怨你在 GetMapping 中定义参数。这很好用:

@GetMapping(value = "/customer/v1/user/{userId}/purchase")
public ResponseDto Test(@PathVariable("userId") String userId,@RequestParam("productId") String productId ){
    return  new ResponseDto();
}

它会自动把productId后面的值放到productId变量的url里面。

如果您想添加并非总是需要的 @RequestParam 元素,您可以这样定义它们:@RequestParam(value = "count", required=false) String count,请注意 required 部分? Spring 如果您根据需要定义它并且没有在 url 中传递它,则会引发错误。您还可以定义 defaultValue 来解决您的问题。参见 Spring Docs

您不需要在@GetMapping 的值中指定"productId"。会自动拾取。