gpt4 book ai didi

java - Servlet 与过滤器

转载 作者:IT老高 更新时间:2023-10-28 20:26:26 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com