servlet 的根 URL [英] Root URl of the servlet
问题描述
我想从 servlet 之一获取我的 Web 应用程序的根 url.
I want to get the root url of my web application from one of the servlet.
如果我在www.mydomain.com"中部署我的应用程序,我想获得像http://www.mydomain.com".
If I deploy my application in "www.mydomain.com" I want to get the root url like "http://www.mydomain.com".
同样的事情,如果我将它部署在具有 8080 端口的本地 tomcat 服务器中,它应该给 http://localhost:8080/myapp
Same thing if I deploy it in local tomcat server with 8080 port it should give http://localhost:8080/myapp
谁能告诉我如何从 servlet 获取我的 Web 应用程序的根 URL?
Can anyone tell me how to get the root URL of my web application from servlet?
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(和/或在他的浏览器中键入)和部署 servlet 的容器所提供的 URL 可能非常不同?
You do realize that the URL client sees (and/or types into his browser) and the URL served by the container your servlet is deployed on can be very different?
不过,为了获得后者,您可以在 HttpServletRequest:
In order to get the latter, though, you have a few methods available on HttpServletRequest:
- 您可以调用
getScheme()
、getServerName()
、getServerPort()
和getContextPath()
并使用适当的分隔符将它们组合起来 - 或者您可以调用
getRequestURL()
并从中删除getServletPath()
和getPathInfo()
.
- You can either call
getScheme()
,getServerName()
,getServerPort()
andgetContextPath()
and combine them using appropriate separators - OR you can call
getRequestURL()
and removegetServletPath()
andgetPathInfo()
from it.
这篇关于servlet 的根 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!