100

Here's the scenario.

My Java web application has following path

https://www.mywebsite.com:9443/MyWebApp

Let's say there is a JSP file

https://www.mywebsite.com:9443/MyWebApp/protected/index.jsp

and I need to retrieve

https://www.mywebsite.com:9443/MyWebApp 

within this JSP file.

Of course, there is rather a lazy and silly way of just getting the URL and then re-tracing the path back.

But is there a programatic way of doing this? Specifically, I think I can get the domain + port, but how do I actually retrieve the application name "MyWebApp"?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
ericbae
  • 9,604
  • 25
  • 75
  • 108

6 Answers6

110

Take a look at the documentation for HttpServletRequest.
In order to build the URL in your example you will need to use:

  • getScheme()
  • getServerName()
  • getServerPort()
  • getContextPath()

Here is a method that will return your example:

public static String getURLWithContextPath(HttpServletRequest request) {
   return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
}
bluish
  • 26,356
  • 27
  • 122
  • 180
Jataro
  • 2,548
  • 1
  • 17
  • 17
  • 1
    how to get the ip in case the servername was localhost ? – Mahmoud Saleh Nov 11 '12 at 14:15
  • just quick note, getScheme() doesn't always work for https, some servers have weird behavior and may always return http instead of https. i thought that i should let u know. try request.getRequestURL().toString() and massage if u need – K'' Mar 08 '13 at 19:05
  • 1
    @MahmoudSaleh `request.getLocalAddr()` – bluish Mar 21 '13 at 07:51
  • It will be good if you also show the example output for each of the methods. It is a pain to get a web-server up and running just to check what the output of each might be. – Jus12 Dec 09 '13 at 15:33
  • 1
    `getContextPath()` in the method doesn't return anything! And `getServerPort()` returns only a 2 digit number, not a 4 digit number! Could I avail some help on it? – vss Jun 23 '17 at 07:38
94

The web application name (actually the context path) is available by calling HttpServletrequest#getContextPath() (and thus NOT getServletPath() as one suggested before). You can retrieve this in JSP by ${pageContext.request.contextPath}.

<p>The context path is: ${pageContext.request.contextPath}.</p>

If you intend to use this for all relative paths in your JSP page (which would make this question more sense), then you can make use of the HTML <base> tag:

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<c:set var="req" value="${pageContext.request}" />
<c:set var="url">${req.requestURL}</c:set>
<c:set var="uri" value="${req.requestURI}" />

<!doctype html>
<html lang="en">
    <head>
        <title>SO question 2204870</title>
        <base href="${fn:substring(url, 0, fn:length(url) - fn:length(uri))}${req.contextPath}/">
        <script src="js/global.js"></script>
        <link rel="stylesheet" href="css/global.css">
    </head>
    <body>
        <ul>
            <li><a href="home.jsp">Home</a></li>
            <li><a href="faq.jsp">FAQ</a></li>
            <li><a href="contact.jsp">Contact</a></li>
        </ul>
    </body>
</html>

All links in the page will then automagically be relative to the <base> so that you don't need to copypaste the context path everywhere. Note that when relative links start with a /, then they will not be relative to the <base> anymore, but to the domain root instead.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Doc states, "The context path returned by `ServletContext.getContextPath()` should be considered as the prime or preferred context path of the application". That was the reason I included this one to my original answer, after realizing the thing. I didn't remove my first attempt, as I want the OP to consider reading through the docs and know a little more about related methods. I hope you are getting my point. – Adeel Ansari Feb 05 '10 at 14:02
  • @Vinegar: For JSP files, the `getServletPath()` returns `/filename.jsp`. The OP wasn't asking for that at all, this is certainly not the way to go. – BalusC Feb 05 '10 at 14:25
  • I would certainly make correction in my post, but this time I was expecting the response to my comment, which is entirely different :). – Adeel Ansari Feb 08 '10 at 09:44
  • 2
    In XHTML DOCTYPE, you will need to append a '/' character to the contextPath. – Basil Musa Apr 16 '12 at 11:18
  • Why didn't you close the `` tag? Shouldn't all tag be closed? – Fabiano Francesconi Jan 03 '14 at 18:17
  • I got curious and had to look it up: [Base Tag](http://www.w3schools.com/tags/tag_base.asp) – burnttoast11 May 20 '14 at 18:59
  • Note: The `` for the url is different because getRequestURL() returns a StringBuffer. Putting the EL value in the body of a set tag instead of the value attribute implicitly calls toString() on the object. – MALfunction84 Feb 26 '15 at 20:59
  • This is really helpful. is powerful tool. – mahesh nanayakkara May 24 '15 at 13:20
33

The application name come from getContextPath.

I find this graphic from Agile Software Craftsmanship HttpServletRequest Path Decoding sorts out all the different methods that are available:

enter image description here

AgilePro
  • 5,588
  • 4
  • 33
  • 56
  • 2
    This graphic is useful for answering many questions. I have tried to use it in the answer to many questions, but they were all deleted: there is a rule against re-using the same answer. Which is a shame. The theory is that if you use the same answer, then the questions must be the same, and therefor you should just mark the question as duplicate. But that is not reality. There are many different questions that can be answered with the same graphic. It is small-minded to implement such arbitrary rules. If YOU see a question that is best answered with this graphic, please use it. – AgilePro Apr 04 '19 at 21:03
7

I would strongly suggest you to read through the docs, for similar methods. If you are interested in context path, have a look here, ServletContext.getContextPath().

Adeel Ansari
  • 39,541
  • 12
  • 93
  • 133
4

The following code might be useful for web application using JavaScript.

var newURL = window.location.protocol + "//"  + window.location.host + "" + window.location.pathname;

newURL = newURL.substring(0,newURL.indexOf(""));
Tiny
  • 27,221
  • 105
  • 339
  • 599
0

If you are being passed a url as a String and want to extract the context root of that application, you can use this regex to extract it. It will work for full urls or relative urls that begin with the context root.

url.replaceAll("^(.*\\/\\/)?.*?\\/(.+?)\\/.*|\\/(.+)$", "$2$3")
master_d
  • 27
  • 1