Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get request URL in JSP which is forwarded by Servlet

Tags:

url

jsp

servlets

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.

like image 661
user12384512 Avatar asked Jun 07 '10 13:06

user12384512


People also ask

How do I forward a servlet request?

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.


2 Answers

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']} 
like image 140
axtavt Avatar answered Sep 27 '22 19:09

axtavt


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; } 
like image 41
Koss Avatar answered Sep 27 '22 19:09

Koss