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

让人想犯罪 __ 提交于 2019-12-18 05:05:16

问题


I want to create a filter 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.


回答1:


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.




回答2:


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.




回答3:


"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.



来源:https://stackoverflow.com/questions/4324176/how-to-make-a-filter-to-detect-if-the-user-requested-a-page-that-is-not-found

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!