如何在Spring Boot中创建/调用带有路径和请求参数的REST控制器?

huangapple go评论93阅读模式
英文:

How to create/call a rest controller in springboot with both path and request parameter

问题

我有这个Spring Boot中的Rest控制器方法:

@GetMapping("/cghsHcoSearchText/cityId/{cityId}/hcoName/{hcoName}/treatmentName/{treatmentName}")
public String cghsHcoSearchText(@PathVariable String cityId, @RequestParam(name = "hcoName", required = false) String hcoName, 
        @RequestParam(name = "treatmentName", required = false) String treatmentName) {
    return "Some Text";
}

它有一个PathVariable和两个可选的Request参数。

现在,当我使用treatmentName = null访问这个URL时,我得到了Whitelabel Error Page

http://localhost:8082/cghs/cghsHcoSearchText/cityId/011?hcoName=Guru?

任何帮助都将不胜感激。

英文:

I have this rest controller method in springboot

@GetMapping("/cghsHcoSearchText/cityId/{cityId}/hcoName/{hcoName}/treatmentName/{treatmentName}")
	public String cghsHcoSearchText(@PathVariable String cityId, @RequestParam(name = "hcoName", required = false) String hcoName, 
			@RequestParam(name = "treatmentName", required = false) String treatmentName) {
		return "Some Text";
	}

It has one PathVariable and 2 optional Request parameter.

Now when I hit this url with treatmentName = null i get Whitelabel Error Page

http://localhost:8082/cghs/cghsHcoSearchText/cityId/011?hcoName=Guru?

Any help will be appreciated.

答案1

得分: 2

@GetMapping("hello/{id}")
public ResponseEntity printInfo(@PathVariable("id") String id,
@RequestParam(required = false, name = "name") String name) {
System.out.println(id + " " + name);
return new ResponseEntity<>(HttpStatus.OK);
}


<details>
<summary>英文:</summary>

We should not specify request param as a placeholder in URL mapping. Only the path params should be mentioned in placeholder. Sharing a code snippet and corresponding URL which will help out in understanding this

    @GetMapping(&quot;hello/{id}&quot;)
    	public ResponseEntity&lt;Void&gt; printInfo(@PathVariable(&quot;id&quot;) String id,
    			@RequestParam(required = false, name = &quot;name&quot;) String name) {
    		System.out.println(id + &quot;   &quot; + name);
    		return new ResponseEntity&lt;&gt;(HttpStatus.OK);
    	}

Here id comes as a path param and name as a request param which is not mentioned in mapping annotation.

URL would look like 

    http://localhost:8080/hello/234?name=pappi

</details>



huangapple
  • 本文由 发表于 2020年7月22日 23:13:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/63037553.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定