JAVA SERVLET - Requested URI
But the one problem i had was trying to obtain the correct value of the URI that was requested. You would think that calling the method "getRequestURI()" of the HttpServletRequest would do the trick... But not so....
//Using the full class name for reference only,
//the parameter name should be used instead
String uri = HttpServletRequest.getRequestURI();
System.out.println("URI: " + uri);
This would be great if i made a request to "http://www.mydomain.com/myServletExceptionHandler"
But my test request was made to "http://www.mydomain.com/build/table" and that's what i was expecting to see once i printed the value of "getRequestURI()" But that wasn't the case.
So after some heavy digging around, i stumbled apon a solution that was embedded within the attributes of the request.
String uri = null;
uri = HttpServletRequest.getAttribute("javax.servlet.error.request_uri");
System.out.println("URI: " + uri);
The above code resulted in this output: URI: /build/table
This was great, since i had made my request to "http://www.mydomain.com/build/table" the code was outputting the correct results. But there's a catch here.... This only worked when there was an error thrown and handled by the Servlet, but if no error was thrown, the output was: URI: (blank no output shown). The value remained null, and would throw an error if processed further. So here comes an if statement and the use of the "getRequestedURI()" method.
String uri = null;
uri = HttpServletRequest.getAttribute("javax.servlet.error.request_uri");
if (uri == null) {
//in case there's no URI given
uri = HttpServletRequest.getRequestURI();
}
System.out.println("URI: " + uri);
This did the trick, if an error was thrown the Original requested URI would be pulled from the attributes of the HttpServletRequest class, extracting the "javax.servlet.error.request_uri" value. If the String Object remains null, and attempt is made to retrive a value from the "getRequestedURI()" method of the HttpServletRequest class... And were done....


