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

时间:2018-10-29 14:32:02

标签: java spring spring-boot 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,但仍然没有成功。

2 个答案:

答案 0 :(得分:3)

它抱怨您在GetMapping中定义参数。效果很好:

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

它将自动将值放在productId变量的url中productId之后。

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

答案 1 :(得分:1)

您无需在@GetMapping的值中指定“ productId”。它会被自动提取。