gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 08:26:03 26 4
gpt4 key购买 nike

我正在尝试在 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

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

最佳答案

它提示您在 GetMapping 中定义了参数。这很好用:

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

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

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

关于java - Spring Rest中如何同时使用@Pathvariable和@RequestParam,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53047718/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com