6

How would I get the URL of the page that was requested that caused the 404 error?

For example, I type I go to http://example.com/path/does/not/exist/index.jsp I already have a custom 404 page but how would I go about retrieving the URL mentioned above so that I can display it with a message similar to "The url http://example.com/path/does/not/exist/index.jsp does not exist"?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
alexcoco
  • 6,657
  • 6
  • 27
  • 39
  • possible duplicate of [JSP / Servlet HTTP 404 error handling](http://stackoverflow.com/questions/3336501/jsp-servlet-http-404-error-handling) – BalusC Feb 09 '11 at 18:53

2 Answers2

10

If forward was used to go to the error page, you can obtain the original request URL by

request.getAttribute("javax.servlet.forward.request_uri")

or by EL

${requestScope['javax.servlet.forward.request_uri']}
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
0

I'm using JDK 8 and GlassFish 4, and

request.getAttribute("javax.servlet.forward.request_uri")

always returned null for me. What eventually did work was

request.getAttribute("javax.servlet.error.request_uri")

I'm not sure why the attribute name is different, but in case the name I listed doesn't work on your setup, here's the code I used to find it...

    Enumeration<String> names = request.getAttributeNames();

    while(names.hasMoreElements()){
        String name = names.nextElement();
        Object attr = request.getAttribute(name);

        System.out.println("Req:  "+name + " : "+attr);
    }
user3479450
  • 131
  • 2
  • 3