How to make a filter to detect if the user requested a page that is not found?
I want to create a filt开发者_开发知识库er in my app such that before each request, it detects whether the requested page exists. If it doesn't exist, it will forward the user to an error page.
How do I detect that the page exists?
I need a solution with a filter and not using the web.xml tag method.
If you don't have authentication, you can.
- Make a
Filter
- Use HttpServletResponseWrapper and override the
sendError()
andsetStatus()
- Pass the wrapped response through
chain.doFilter(req, wrapper)
- If you get a
sendError()
in your wrapper, see if it's a 404. - Take appropriate response.
You may also have to override getOutputStream()
and getWriter()
to avoid the response to be flushed to the client before you get a chance to do stuff.
You can directly configure it in web.xml
<error-page>
<error-code>404</error-code>
<location>/yourCustom404.jsp</location>
</error-page>
Or Create a filter and Use HTTPURLConnection programatically detect the page exist or not.
"Page exists" is not something trivial. Pages need not to exist physically as files.
Apart from the option mentioned by org.life.java to simulate a request using HttpURLConnection
, you can create a HttpServletResponseWrapper
, override the setStatus
method, and whenever it is set to 404
, take extra measures.
精彩评论