如何获取没有上下文路径的请求URI? [英] How to get request URI without context path?

查看:358
本文介绍了如何获取没有上下文路径的请求URI?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

方法请求。 getRequestURI()返回带有上下文路径的URI。

The Method request.getRequestURI() returns URI with context path.

例如,如果应用程序的基本URL是 http:// localhost:8080 / myapp / (即上下文路径是 myapp ),我为 http:// localhost:8080调用 request.getRequestURI() / myapp / secure / users ,它将返回 / myapp / secure / users

For example, if the base URL of an application is http://localhost:8080/myapp/ (i.e. the context path is myapp), and I call request.getRequestURI() for http://localhost:8080/myapp/secure/users, it will return /myapp/secure/users.

我们有没有办法只获得这部分 / secure / users ,即没有上下文路径的URI?

Is there any way we can get only this part /secure/users, i.e. the URI without context path?

推荐答案

如果你在一个映射在前缀模式上的前控制器servlet中,那么你可以只使用 HttpServletRequest#getPathInfo( )

If you're inside a front contoller servlet which is mapped on a prefix pattern, then you can just use HttpServletRequest#getPathInfo().

String pathInfo = request.getPathInfo();
// ...

假设示例中的servlet映射到 / secure ,然后这将返回 / users ,这将是典型前端控制器servlet中唯一感兴趣的信息。

Assuming that the servlet in your example is mapped on /secure, then this will return /users which would be the information of sole interest inside a typical front controller servlet.

但是,如果servlet映射到后缀模式(但是您的URL示例并未表明是这种情况),或者当您实际位于过滤器内时(当还没有确定要调用的servlet,所以 getPathInfo()可以返回 null ),那么你最好的赌注是使用通常的 String 方法根据上下文路径的长度自己对请求URI进行子串:

If the servlet is however mapped on a suffix pattern (your URL examples however does not indicate that this is the case), or when you're actually inside a filter (when the to-be-invoked servlet is not necessarily determined yet, so getPathInfo() could return null), then your best bet is to substring the request URI yourself based on the context path's length using the usual String method:

HttpServletRequest request = (HttpServletRequest) req;
String path = request.getRequestURI().substring(request.getContextPath().length());
// ...

这篇关于如何获取没有上下文路径的请求URI?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆