How can I get request URL in JSP which is forwarded by Servlet?
If I run following code in JSP,
System.out.println("servlet path= " + request.getServletPath()); System.out.println("request URL= " + request.getRequestURL()); System.out.println("request URI= " + request.getRequestURI());
then I get the server side path to the JSP. But I want to get the URL as you can see in browser's address bar. I can get it in the Servlet that forwards to the JSP, but I want to get it within the JSP.
forward() method This method forwards a request from a servlet to another servlet on the same server. It allows one servlet to do the initial processing of a request, obtains the RequestDispatcher object, and forwards the request to another servlet to generate the response.
If you use RequestDispatcher.forward()
to route the request from controller to the view, then request URI is exposed as a request attribute named javax.servlet.forward.request_uri
. So, you can use
request.getAttribute("javax.servlet.forward.request_uri")
or
${requestScope['javax.servlet.forward.request_uri']}
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With