仅从httpservletrequest获取uri

snvhrwxg  于 2021-07-06  发布在  Java
关注(0)|答案(2)|浏览(284)

我有一个api- http://localhost:8080/api/version/<versionA> 其中versiona是路径参数。
HttpServlet请求 getRequestURI() returns -> /api/version/<versionA> 我们如何确保 /api/version 他回来了吗?是否有任何方法可以对所有端点进行泛化,只返回uri的第一部分(不包括路径参数)?例如-

/api/version/<param1> Should Return /api/version
/api/<param1> Should return /api
/api/version/<param1>/name/<param2> Should return /api/version
wljmcqd8

wljmcqd81#

路径参数不是查询参数;它是url路径的一部分/段。因此,没有(也不应该有)内置的ServletAPI方法,它将返回您的“自定义子字符串”路径。
问:为什么?
答:因为您可能有多个路径参数 /a/b/<param1>/<param2>/c/<param3> 是否有任何方法可以对所有端点进行泛化,只返回uri的第一部分(不包括路径参数)?
在您的例子中,一个选项是实现一些实用方法,它将找到 "/" 然后将子字符串返回到最后一个 "/" .

zxlwwiss

zxlwwiss2#

这在一定程度上取决于你是如何构建事物的,但让我们举个例子。

http://localhost:8080/sample/rest/v1/classLevel/methodLevel/param1/param2/something/param3

服务定义为:

@Path("/v1/classLevel")
public class NewService {

    @Path("/methodLevel/{param1}/{param2}/something/{param3}")
    public Response getSomeStuff(@PathParam("param1") String param1,
                                 @PathParam("param2") String param2,
                                 @PathParam("param3") String param3,
                                 @Context HttpServletRequest request) {
        return Response.ok().build();
    }
}

此webapp部署在上下文根“sample”下。也就是说如果我要去 http://localhost:8080/sample/ 我会得到webapp的根元素(也许是index.html)。在我的申请表中,我有:

@ApplicationPath("/rest")
public class RestApplicationConfig extends Application {
    // intentionally empty
}

所以url中的参数是: request.getServletPath() 返回“/rest” request.getContextPath() 返回“/示例” request.getPathInfo() 返回“/v1/classlevel/methodlevel/param1/param2/something/param3”
所以我相信你想要的是 request.getContextPath() + request.getServletPath() . 但你到底需要哪一部分还不清楚。
编辑以找出类级别上的路径需要一些反射。在被调用的类中(即 NewService 你可以通过以下方式获得:

public String getClassLevelPath() {
    if( this.getClass().isAnnotationPresent(Path.class)) {
        Path annotation = this.getClass().getAnnotation(Path.class);
        return annotation.value();
    }

    return null;
}

当我的类被定义时,它返回“/v1/classlevel”。我个人会把它缓存在一个静态变量中,因为它在运行时是不会改变的,除非你做了其他事情来改变它。

相关问题