我想从一个servlet获取我的Web应用程序的根URL.
如果我在"www.mydomain.com"中部署我的应用程序,我想获得像" http://www.mydomain.com " 这样的根URL .
如果我将它部署在具有8080端口的本地tomcat服务器中它应该给予同样的事情 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
}
}
Run Code Online (Sandbox Code Playgroud)
Chs*_*y76 38
您确实意识到URL客户端看到(和/或键入其浏览器),并且您的servlet部署在容器上的URL可能会有很大不同?
但是,为了获得后者,您可以在HttpServletRequest上使用一些方法:
getScheme(),getServerName(),getServerPort()并getContextPath()使用适当的分隔符将它们组合起来getRequestURL()和删除getServletPath(),并getPathInfo()从它.Ben*_*uer 13
此功能可帮助您从以下位置获取基本URL HttpServletRequest:
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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
49263 次 |
| 最近记录: |