Try this instead:
String scheme = req.getScheme();
String serverName = req.getServerName();
int serverPort = req.getServerPort();
String uri = (String) req.getAttribute("javax.servlet.forward.request_uri");
String prmstr = (String) req.getAttribute("javax.servlet.forward.query_string");
String url = scheme + "://" +serverName + ":" + serverPort + uri + "?" + prmstr;
Note: You can't get HREF anchor from your url. Example, if you have url "toc.html#top" then you can get only "toc.html"
Note: req.getAttribute("javax.servlet.forward.request_uri") work only in JSP. if you run this in controller before JSP then result is null
You can use code for both variant:
public static String getCurrentUrl(HttpServletRequest req) {
String url = getCurrentUrlWithoutParams(req);
String prmstr = getCurrentUrlParams(req);
url += "?" + prmstr;
return url;
}
public static String getCurrentUrlParams(HttpServletRequest request) {
return StringUtil.safeString(request.getQueryString());
}
public static String getCurrentUrlWithoutParams(HttpServletRequest request) {
String uri = (String) request.getAttribute("javax.servlet.forward.request_uri");
if (uri == null) {
return request.getRequestURL().toString();
}
String scheme = request.getScheme();
String serverName = request.getServerName();
int serverPort = request.getServerPort();
String url = scheme + "://" + serverName + ":" + serverPort + uri;
return url;
}