Java servlet的根URl
我想从一个servlet获取web应用程序的根url 如果我在“www.mydomain.com”中部署我的应用程序,我希望获得类似“”的根url 如果我将它部署在本地tomcat服务器上,它应该提供8080端口Java servlet的根URl,java,jakarta-ee,Java,Jakarta Ee,我想从一个servlet获取web应用程序的根url 如果我在“www.mydomain.com”中部署我的应用程序,我希望获得类似“”的根url 如果我将它部署在本地tomcat服务器上,它应该提供8080端口http://localhost:8080/myapp 有人能告诉我如何从servlet获取web应用程序的根URL吗 public class MyServlet extends HttpServlet { @Override protected void doPos
http://localhost:8080/myapp
有人能告诉我如何从servlet获取web应用程序的根URL吗
public class MyServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String rootURL="";
//Code to get the URL where this servlet is deployed
}
}
您是否意识到,客户机看到的URL(和/或在其浏览器中键入的URL)和部署servlet的容器提供的URL可能非常不同 不过,为了获得后者,您有以下几种方法:
- 您可以调用
、getScheme()
、getServerName()
和getServerPort()
并使用适当的分隔符将它们组合起来getContextPath()
- 或者您可以调用
并从中删除getRequestURL()
和getServletPath()
getPathInfo()
String rootUrl=RootContextUtil.getInstance().getRootURL()代码>
注意:无需担心协议/端口等。。希望这对每个人都有帮助此功能可帮助您从HttpServletRequest
获取基本URL:
public static String getBaseUrl(HttpServletRequest request) {
String scheme = request.getScheme() + "://";
String serverName = request.getServerName();
String serverPort = (request.getServerPort() == 80) ? "" : ":" + request.getServerPort();
String contextPath = request.getContextPath();
return scheme + serverName + serverPort + contextPath;
}
我相信,在OP的例子中,myapp
是一个servlet名称/路径。你说呢?String rootUrl=request.getRequestURL().toString().replace(request.getRequestURI(),“”)@Sllouyssgort不工作,因为getRequestURI()
包括myapp
public static String getBaseUrl(HttpServletRequest request) {
String scheme = request.getScheme();
String host = request.getServerName();
int port = request.getServerPort();
String contextPath = request.getContextPath();
String baseUrl = scheme + "://" + host + ((("http".equals(scheme) && port == 80) || ("https".equals(scheme) && port == 443)) ? "" : ":" + port) + contextPath;
return baseUrl;
}