How to get only part of URL from HttpServletRequest?
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 );
You say you want to get exactly:
http://localhost:9090/dts
In your case, the above string consist of:
- scheme: http
- server host name: localhost
- server port: 9090
- context path: dts
(More info about the elements of a request path can be found in the official Oracle Java EE Tutorial: Getting Information from Requests)
##First variant:###
String scheme = request.getScheme();
String serverName = request.getServerName();
int serverPort = request.getServerPort();
String contextPath = request.getContextPath(); // includes leading forward slash
String resultPath = scheme + "://" + serverName + ":" + serverPort + contextPath;
System.out.println("Result path: " + resultPath);
##Second variant:##
String scheme = request.getScheme();
String host = request.getHeader("Host"); // includes server name and server port
String contextPath = request.getContextPath(); // includes leading forward slash
String resultPath = scheme + "://" + host + contextPath;
System.out.println("Result path: " + resultPath);
Both variants will give you what you wanted: http://localhost:9090/dts
Of course there are others variants, like others already wrote ...
It's just in your original question you asked about how to get http://localhost:9090/dts
, i.e. you want your path to include scheme.
In case you still doesn't need a scheme, the quick way is:
String resultPath = request.getHeader("Host") + request.getContextPath();
And you'll get (in your case): localhost:9090/dts