user1732653 user1732653 - 5 months ago 8
Java Question

How to get only part of URL from HttpServletRequest?

From the following URL I need to get

(http://localhost:9090/dts)
alone.

That is I need to remove
(documents/savedoc)
(OR)

need to get only -
(http://localhost:9090/dts)


http://localhost:9090/dts/documents/savedoc


Is there any method available in request to get the above?

I tried the following and got the result. But still trying.

System.out.println("URL****************"+request.getRequestURL().toString());
System.out.println("URI****************"+request.getRequestURI().toString());
System.out.println("ContextPath****************"+request.getContextPath().toString());

URL****************http://localhost:9090/dts/documents/savedoc
URI****************/dts/documents/savedoc
ContextPath****************/dts


Can anyone please help me in fixing this?

Answer

AFAIK for this there is no API provided method, need to customization.

String serverName = request.getServerName();
int portNumber = request.getServerPort();
String contextPath = request.getContextPath();

// try this

System.out.println(serverName + ":" +portNumber + contextPath );
Comments