Servlet vs Filter [英] Servlet vs Filter
问题描述
Servlet 和过滤器有什么区别?你建议用什么来授权页面?
What is the difference between a Servlet and Filter? What do you recommend to use for authorization to pages?
推荐答案
使用过滤器
当您想要根据特定条件过滤和/或修改请求时。如果要控制,预处理和/或后处理请求,请使用 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资源有任何依赖性;通过这种方式,它可以由多种类型的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:
- 查询请求并采取相应行动。
- 阻止请求和响应对进一步传递。
- 修改请求标头和数据。您可以通过提供请求的自定义版本来执行此操作。
- 修改响应标头和数据。您可以通过提供自定义版本的响应来实现此目的。
- 与外部资源交互。
- 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.
对于授权,过滤器
是最合适的。以下是过滤器如何检查已登录用户请求的基本启动示例:
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 vs Filter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!