views:

977

answers:

3

Hi all

I'm having trouble building an absolute URL from a relative URL without resorting to String hackery...

Given

http://localhost:8080/myWebApp/someServlet

Inside the method:

   public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}

What's the most "correct" way of building :

http://localhost:8080/myWebApp/someImage.jpg

(Note, must be absolute, not relative)

Currently, I'm doing it through building the string, but there MUST be a better way.

I've looked at various combinations of new URI / URL, and I end up with

http://localhost:8080/someImage.jpg

Help greatly appreciated

Thanks

Marty

A: 

Looks like you already figured out the hard part, which is what host your are running on. The rest is easy,

String url = host + request.getContextPath() + "/someImage.jpg";

Should give you what you need.

ZZ Coder
A: 

How about:

String s = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/someImage.jpg";
JRL
+1  A: 

Using java.net.URL

 URL baseUrl = new URL("http:www.google.com/someFolder/");
 URL url = new URL( baseURL , "../test.html");
Hamza Yerlikaya