Servlet 与过滤器 [英] Servlet vs Filter

查看:54
本文介绍了Servlet 与过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Servlet过滤器 之间有什么区别?您建议使用什么来授权页面?

What is the difference between a Servlet and Filter? What do you recommend to use for authorization to pages?

推荐答案

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

Use a Filter when you want to filter and/or modify requests based on specific conditions. Use a Servlet when you want to control, preprocess and/or postprocess requests.

Java EE 教程 提到了以下有关过滤器的内容:

The Java EE tutorial mentions the following about filters:

过滤器是一个对象,可以转换请求或响应的标头和内容(或两者).过滤器与 Web 组件的不同之处在于过滤器本身通常不会创建响应.相反,过滤器提供可以附加"到任何类型的 Web 资源的功能.因此,过滤器不应依赖它作为过滤器的 Web 资源;这样它就可以由不止一种类型的网络资源组成.

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:

  • 查询请求并采取相应措施.
  • 阻止请求和响应对进一步传递.
  • 修改请求头和数据.为此,您可以提供请求的自定义版本.
  • 修改响应头和数据.为此,您可以提供自定义版本的响应.
  • 与外部资源互动.

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

For authorization, a Filter is the best suited. Here's a basic kickoff example of how a filter checks requests for the logged-in user:

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);
    }
}

这篇关于Servlet 与过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆