java - Servlet 与过滤器

标签 java servlets servlet-filters

ServletFilter 有什么区别?您建议使用什么来授权页面?

最佳答案

当您想根据特定条件过滤和/或修改请求时,请使用 Filter。当您想要控制、预处理和/或后处理请求时,请使用 Servlet

Java EE tutorial提到以下有关过滤器的内容:

A filter is an object that can transform the header and content (or both) of a request or response. Filters differ from web components in that filters usually do not themselves create a response. Instead, a filter provides functionality that can be “attached” to any kind of web resource. Consequently, a filter should not have any dependencies on a web resource for which it is acting as a filter; this way it can be composed with more than one type of web resource.

The main tasks that a filter can perform are as follows:

  • Query the request and act accordingly.
  • Block the request-and-response pair from passing any further.
  • Modify the request headers and data. You do this by providing a customized version of the request.
  • Modify the response headers and data. You do this by providing a customized version of the response.
  • Interact with external resources.

对于授权,Filter 是最合适的。以下是过滤器如何检查登录用户请求的基本启动示例:

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
    if (((HttpServletRequest) request).getSession().getAttribute("user") == null) {
        // User is not logged in. Redirect to login page.
        ((HttpServletResponse) response).sendRedirect("login");
    } else {
        // User is logged in. Just continue with request.
        chain.doFilter(request, response);
    }
}

关于java - Servlet 与过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2957165/

相关文章:

java - 打印所有没有元素相邻的子序列数组

java - 从代码中的任何位置访问 HttpContext、HttpServletRequest 和 HttpServletResponse

java - "/"和 "/*"和有什么区别?

servlets - 调整 web.xml 监听器、过滤器和 servlet

java - 如何更改java过滤器中的servlet请求主体?

java - maven.springframework.org/release 已缓存在本地存储库中

java - 数据驱动规则引擎 - Drools

java - notify/notifyall 是否释放被持有的锁

java - 如何在servlet中查询insert postgresql

java - 使用 ASP .NET 中的 Servlet