Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
150 views
in Technique[技术] by (71.8m points)

java - Root URl of the servlet

I want to get the root url of my web application from one of the servlet.

If I deploy my application in "www.mydomain.com" I want to get the root url like "http://www.mydomain.com".

Same thing if I deploy it in local tomcat server with 8080 port it should give http://localhost:8080/myapp

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

    }
}
question from:https://stackoverflow.com/questions/1629102/root-url-of-the-servlet

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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?

In order to get the latter, though, you have a few methods available on HttpServletRequest:

  • You can either call getScheme(), getServerName(), getServerPort() and getContextPath() and combine them using appropriate separators
  • OR you can call getRequestURL() and remove getServletPath() and getPathInfo() from it.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...