java—如何在spring应用程序中从url获取延续Map?

ui7jx7zq  于 2021-07-05  发布在  Java
关注(0)|答案(2)|浏览(309)

我有一个spring应用程序,我想从url获取值,例如:
发送到spring应用程序的url是 www.example.com/app/account/register . 我怎么才能拿到钱 /register 之后的部分 /account 当我的代码看起来像这样的时候。
我用了这个例子 /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;
    }
}
vh0rcniy

vh0rcniy1#

使用uricomponentsbuilder作为参数,它将被spring注入并用当前uri初始化。然后可以转换为uricomponents uricomponents来查询路径。

@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;
    }
}
b0zn9rqh

b0zn9rqh2#

你可以用 @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;
    }
}

相关问题