开发者

How to make a filter to detect if the user requested a page that is not found?

开发者 https://www.devze.com 2023-01-27 15:00 出处:网络
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.

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.

  1. Make a Filter
  2. Use HttpServletResponseWrapper and override the sendError() and setStatus()
  3. Pass the wrapped response through chain.doFilter(req, wrapper)
  4. If you get a sendError() in your wrapper, see if it's a 404.
  5. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消