3

I am running my application in localhost, port 8080. The base url is: http://localhost:8080/EMSApplication/otherparts...

Now from HttpServletRequest how can I extract the portion http://localhost:8080/EMSApplication ?

Currently I am doing this:

String schema = request.getScheme();
String serverName = request.getServerName();
int serverPort = request.getServerPort();
String contextPath = request.getContextPath();
String path = schema + "://" + serverName + ":" + serverPort + contextPath;
System.out.println(path);

Here request is the instance of HttpServletRequest.

Is this procedure right?

Is there any other way to get the information?

If I host my application and say the URL is http://my.domain.com/EMSApplication/otherparts... then there the aforesaid procedure code will work?


Another way I found:

String requestUrl = request.getRequestURL().toString();
String contextPath = request.getContextPath();
String path = requestUrl.substring(0, requestUrl.indexOf(contextPath) + contextPath.length());

Where I need this:

HttpServletRequest request = (HttpServletRequest) getRequest().getContainerRequest();
String requestUrl = request.getRequestURL().toString();
String contextPath = request.getContextPath();
String path = requestUrl.substring(0, requestUrl.indexOf(contextPath) + contextPath.length());          
submitLink.add(new WebMarkupContainer("submitImage").add(new AttributeModifier("src", path + "/ASSETS/css/images/login-btn.png")));

I am developing an Wicket application where I need to specify src of an <img/>.

1 Answer 1

2

Either way is fine, but I prefer the first. There isn't anything more direct that comes to mind, although if you explained why you want this value, there might be.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. I have updated my answer to explain the scenario. Can you tell me why would you prefer the first one?
I prefer the first since the second will break for the root context where the context path is a zero length string. Given what you are doing, there are probably some optimizations you can make to save doing the same thing multiple times but there is nothing that comes to mind in the Servlet API that would help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.