ChatGPT解决这个技术问题 Extra ChatGPT

How to get domain URL and application name?

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"?


b
bluish

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();
}

how to get the ip in case the servername was localhost ?
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
@MahmoudSaleh request.getLocalAddr()
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.
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?
B
BalusC

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.


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.
@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.
I would certainly make correction in my post, but this time I was expecting the response to my comment, which is entirely different :).
In XHTML DOCTYPE, you will need to append a '/' character to the contextPath.
Why didn't you close the <base> tag? Shouldn't all tag be closed?
A
AgilePro

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:

https://i.stack.imgur.com/btajG.png


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.
A
Adeel Ansari

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().


T
Tiny

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(""));

m
master_d

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")

关注公众号,不定期副业成功案例分享
Follow WeChat

Success story sharing

Want to stay one step ahead of the latest teleworks?

Subscribe Now

相似问题