英文:
How do I get the continuation mapping from the URL in a Spring application?
问题
我有这个Spring应用程序,我想从URL中获取值,例如:
发送到Spring应用程序的URL是www.example.com/app/account/register
。当我的代码看起来像这样时,我如何获取/account
之后的/register
部分。
对于这个示例,我使用了/register
,但这也可以是/login
、/something
。
@RestController
@RequestMapping("/app")
public class MainController {
@RequestMapping(value = "/account")
public boolean AccountServer(@RequestHeader HttpHeaders httpHeaders, @RequestBody Map<String, String> payLoad){
return true;
}
}
英文:
I have this spring application where I want to get the values from a URL, for example:
The url send to the spring application is www.example.com/app/account/register
. How do I get the /register
part after /account
when my code looks like this.
For this example I used /register
but this can be /login
, /something
as well.
@RestController
@RequestMapping("/app")
public class MainController {
@RequestMapping(value = "/account")
public boolean AccountServer(@RequestHeader HttpHeaders httpHeaders, @RequestBody Map<String, String> payLoad){
return true;
}
}
答案1
得分: 3
你可以使用 @PathVariable
注解来获取值。
@RestController
@RequestMapping("/app")
public class MainController {
@RequestMapping(value = "/account/{operation}")
public boolean AccountServer(@RequestHeader HttpHeaders httpHeaders,
@RequestBody Map<String, String> payLoad,
@PathVariable("operation") String operation){
return true;
}
}
英文:
You can use the @PathVariable
annotation to get the value.
@RestController
@RequestMapping("/app")
public class MainController {
@RequestMapping(value = "/account/{operation}")
public boolean AccountServer(@RequestHeader HttpHeaders httpHeaders,
@RequestBody Map<String, String> payLoad,
@PathVariable("operation") String operation){
return true;
}
}
答案2
得分: 1
Use UriComponentsBuilder作为参数,它将由Spring注入并初始化为当前URI。然后,您可以将其转换为UriComponents [UriComponents][1]以查询路径。
@RestController
@RequestMapping("/app")
public class MainController {
@RequestMapping(value = "/account")
public boolean AccountServer(UriComponentsBuilder builder, @RequestHeader HttpHeaders httpHeaders, @RequestBody Map<String, String> payLoad){
List<String> pathSegments = builder.build().getPathSegments();
...
return true;
}
}
[1]: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/util/UriComponents.html
英文:
Use UriComponentsBuilder as a parameter, it will be injected by Spring and initialized with current URI. You can then convert to UriComponents UriComponents to query the path.
@RestController
@RequestMapping("/app")
public class MainController {
@RequestMapping(value = "/account")
public boolean AccountServer(UriComponentsBuilder builder, @RequestHeader HttpHeaders httpHeaders, @RequestBody Map<String, String> payLoad){
List<String> pathSegments = builder.build().getPathSegments();
...
return true;
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论