Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make custom 404 page be a forward, not a redirect in Tomcat

I've got a Spring MVC app served in Tomcat. When the user enters a page that isn't found, it displays my default 404 page, as set in web.xml

<error-page>
   <error-code>404</error-code>
   <location>/errors/404/</location>
</error-page>

The problem is that if the user goes to http://mydomain/bad/url

it is redirected to http://mydomain/errors/404/

This is annoying, because if a user types in an incorrect URL it's hard to see what the mistake was and correct it.

After a 404 error, I'd like it to keep the original URL, but display the error page. (i.e. a forward, not a redirect). That's my impression of how most web servers work. Is this possible?

like image 810
Will Glass Avatar asked Oct 18 '10 22:10

Will Glass


People also ask

Should 404 pages redirect?

404s should not always be redirected. 404s should not be redirected globally to the home page. 404s should only be redirected to a category or parent page if that's the most relevant user experience available. It's okay to serve a 404 when the page doesn't exist anymore (crazy, I know).


1 Answers

I don't quite understand why this works the way it does, but...

I've discovered that if you set the status code and have an empty response (or if you try to forward to the error page), Tomcat will redirect to the error page:

((HttpServletResponse) response).setStatus(HttpServletResponse.SC_NOT_FOUND);

But if you ask Tomcat to send the page, it will just forward and leave the URL in the original state, as I'm looking for.

((HttpServletResponse) response).setStatus(HttpServletResponse.SC_NOT_FOUND);
((HttpServletResponse) response).sendError(HttpServletResponse.SC_NOT_FOUND);
like image 162
Will Glass Avatar answered Nov 16 '22 02:11

Will Glass