servlet过滤器 实例

Java Servlet Filter is used to intercept the client request and do some pre-processing. It can also intercept the response and do post-processing before sending to the client in web application. This is the fourth article in the series of Web Applications Tutorial, you might want to check out earlier articles too.

Java Servlet过滤器用于拦截客户端请求并进行一些预处理。 它还可以截取响应并进行后处理,然后再发送到Web应用程序中的客户端。 这是Web应用程序教程系列中的第四篇文章,您可能也想看看之前的文章。

  1. Java Web ApplicationJava Web应用程序
  2. Java Servlet TutorialJava Servlet教程
  3. Servlet Session ManagementServlet会话管理

Servlet过滤器 (Servlet Filter)

In this article, we will lean about the Servlet Filter in Java. We will look into various usage of servlet filter, how can we create a filter and learn its usage with a simple web application.

在本文中,我们将学习Java中的Servlet过滤器。 我们将研究servlet过滤器的各种用法,如何创建过滤器并通过简单的Web应用程序学习其用法。

  1. Why do we have Servlet Filter?为什么会有Servlet筛选器?
  2. Servlet Filter interfaceServlet过滤器接口
  3. Servlet WebFilter annotationServlet WebFilter批注
  4. Servlet Filter configuration in web.xmlweb.xml中的Servlet过滤器配置
  5. Servlet Filter Example for Logging and session validation用于日志记录和会话验证的Servlet筛选器示例
  1. 为什么会有Servlet筛选器? (Why do we have Servlet Filter?)

    In the last article, we learned how we can manage session in web application and if we want to make sure that a resource is accessible only when the user session is valid, we can achieve this using servlet session attributes. The approach is simple but if we have a lot of servlets and jsps, then it will become hard to maintain because of redundant code. If we want to change the attribute name in the future, we will have to change all the places where we have session authentication.

    That’s why we have a servlet filter. Servlet Filters are pluggable java components that we can use to intercept and process requests before they are sent to servlets and response after servlet code is finished and before container sends the response back to the client.

    Some common tasks that we can do with servlet filters are:

    • Logging request parameters to log files.
    • Authentication and autherization of request for resources.
    • Formatting of request body or header before sending it to servlet.
    • Compressing the response data sent to the client.
    • Alter response by adding some cookies, header information etc.

    As I mentioned earlier, servlet filters are pluggable and configured in deployment descriptor (web.xml) file. Servlets and filters both are unaware of each other and we can add or remove a servlet filter just by editing web.xml.

    We can have multiple filters for a single resource and we can create a chain of filters for a single resource in web.xml. We can create a Servlet Filter by implementing javax.servlet.Filter interface.

    在上一篇文章中,我们了解了如何在Web应用程序中管理会话,并且如果要确保仅在用户会话有效时才可访问资源,则可以使用Servlet会话属性来实现此目的。 这种方法很简单,但是如果我们有很多servlet和jsps,那么由于冗余代码,它将变得难以维护。 如果将来要更改属性名称,则必须更改所有具有会话身份验证的位置。

    这就是为什么我们有一个servlet过滤器。 Servlet过滤器是可插入的 Java组件,我们可以使用它们来拦截和处理请求, 然后再将请求发送到Servlet,并 Servlet代码完成之后以及容器将响应发送回客户端之前进行响应。

    我们可以使用servlet过滤器执行的一些常见任务是:

    • 记录请求参数以记录文件。
    • 对资源请求的身份验证和授权。
    • 在将请求正文或标头发送到servlet之前进行格式化。
    • 压缩发送给客户端的响应数据。
    • 通过添加一些cookie,标头信息等来更改响应。

    如前所述, servlet过滤器是可插入的,并在部署描述符(web.xml)文件中进行配置。 Servlet和过滤器彼此都不知道,我们可以仅通过编辑web.xml来添加或删除Servlet过滤器。

    我们可以为单个资源使用多个过滤器,并且可以在web.xml中为单个资源创建过滤器链。 我们可以通过实现javax.servlet.Filter接口来创建Servlet过滤器。

  2. Servlet过滤器接口 (Servlet Filter interface)

    Servlet Filter interface is similar to Servlet interface and we need to implement it to create our own servlet filter. Servlet Filter interface contains lifecycle methods of a Filter and it’s managed by servlet container.

    Servlet Filter interface lifecycle methods are:

    1. void init(FilterConfig paramFilterConfig) – When container initializes the Filter, this is the method that gets invoked. This method is called only once in the lifecycle of filter and we should initialize any resources in this method. FilterConfig is used by container to provide init parameters and servlet context object to the Filter. We can throw ServletException in this method.
    2. doFilter(ServletRequest paramServletRequest, ServletResponse paramServletResponse, FilterChain paramFilterChain) – This is the method invoked every time by container when it has to apply filter to a resource. Container provides request and response object references to filter as argument. FilterChain is used to invoke the next filter in the chain. This is a great example of Chain of Responsibility Pattern.
    3. void destroy() – When container offloads the Filter instance, it invokes the destroy() method. This is the method where we can close any resources opened by filter. This method is called only once in the lifetime of filter.

    Servlet Filter接口类似于Servlet接口,我们需要实现它来创建我们自己的Servlet过滤器。 Servlet筛选器接口包含筛选器的生命周期方法,并且由Servlet容器管理。

    Servlet Filter接口的生命周期方法是:

    1. void init(FilterConfig paramFilterConfig) –容器初始化Filter时,这是被调用的方法。 该方法在过滤器的生命周期中仅被调用一次,我们应该初始化该方法中的所有资源。 容器使用FilterConfig将初始参数和Servlet上下文对象提供给Filter。 我们可以在这种方法中抛出ServletException。
    2. doFilter(ServletRequest paramServletRequest,ServletResponse paramServletResponse,FilterChain paramFilterChain) –这是每次容器必须将过滤器应用于资源时调用的方法。 容器提供请求和响应对象引用以将筛选器作为参数。 FilterChain用于调用链中的下一个过滤器。 这是责任链模式的一个很好的例子。
    3. void destroy() –当容器卸载Filter实例时,它将调用destroy()方法。 这是我们可以关闭由过滤器打开的任何资源的方法。 该方法在过滤器的生命周期中仅被调用一次。
  3. Servlet WebFilter批注 (Servlet WebFilter annotation)

    javax.servlet.annotation.WebFilter was introduced in Servlet 3.0 and we can use this annotation to declare a servlet filter. We can use this annotation to define init parameters, filter name and description, servlets, url patterns and dispatcher types to apply the filter. If you make frequent changes to the filter configurations, its better to use web.xml because that will not require you to recompile the filter class.

    Read: Java Annotations Tutorial

    Servlet 3.0中引入了javax.servlet.annotation.WebFilter ,我们可以使用此注释来声明servlet过滤器。 我们可以使用此批注定义初始化参数,过滤器名称和描述,servlet,URL模式和分派器类型以应用过滤器。 如果您频繁更改过滤器配置,最好使用web.xml,因为这将不需要您重新编译过滤器类。

    阅读Java注释教程

  4. web.xml中的Servlet过滤器配置 (Servlet Filter configuration in web.xml)

    We can declare a servlet filter in web.xml like below.

    <filter><filter-name>RequestLoggingFilter</filter-name> <!-- mandatory --><filter-class>com.journaldev.servlet.filters.RequestLoggingFilter</filter-class> <!-- mandatory --><init-param> <!-- optional --><param-name>test</param-name><param-value>testValue</param-value></init-param>
    </filter>

    We can map a Filter to servlet classes or url-patterns like below.

    Note: While creating the filter chain for a servlet, container first processes the url-patterns and then servlet-names, so if you have to make sure that filters are getting executed in a particular order, give extra attention while defining the filter mapping.

    Servlet Filters are generally used for client requests but sometimes we want to apply filters with RequestDispatcher also, we can use dispatcher element in this case, the possible values are REQUEST, FORWARD, INCLUDE, ERROR and ASYNC. If no dispatcher is defined then it’s applied only to client requests.

    我们可以在web.xml中声明一个servlet过滤器,如下所示。

    <filter><filter-name>RequestLoggingFilter</filter-name> <!-- mandatory --><filter-class>com.journaldev.servlet.filters.RequestLoggingFilter</filter-class> <!-- mandatory --><init-param> <!-- optional --><param-name>test</param-name><param-value>testValue</param-value></init-param>
    </filter>

    我们可以将Filter映射到如下所示的servlet类或url模式。

    注意:在为servlet创建过滤器链时,容器首先处理url模式,然后处理servlet名称,因此,如果必须确保按特定顺序执行过滤器,请在定义过滤器映射时格外注意。

    Servlet过滤器通常用于客户端请求,但有时我们也希望将过滤器与RequestDispatcher一起使用,在这种情况下,我们可以使用调度程序元素,可能的值为REQUEST,FORWARD,INCLUDE,ERROR和ASYNC。 如果未定义调度程序,则仅将其应用于客户端请求。

  5. 用于日志记录和会话验证的Servlet筛选器示例 (Servlet Filter Example for Logging and session validation)

    In our servlet filter example, we will create filters to log request cookies and parameters and validate session to all the resources except static HTMLs and LoginServlet because it will not have a session.

    We will create a dynamic web project ServletFilterExample whose project structure will look like the below image.

    login.html is the entry point of our application where the user will provide the login id and password for authentication.

    login.html code:

    LoginServlet is used to authenticate the request from the client for login.

    package com.journaldev.servlet.session;import java.io.IOException;
    import java.io.PrintWriter;import javax.servlet.RequestDispatcher;
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.Cookie;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;/*** Servlet implementation class LoginServlet*/
    @WebServlet("/LoginServlet")
    public class LoginServlet extends HttpServlet {private static final long serialVersionUID = 1L;private final String userID = "admin";private final String password = "password";protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {// get request parameters for userID and passwordString user = request.getParameter("user");String pwd = request.getParameter("pwd");if(userID.equals(user) && password.equals(pwd)){HttpSession session = request.getSession();session.setAttribute("user", "Pankaj");//setting session to expiry in 30 minssession.setMaxInactiveInterval(30*60);Cookie userName = new Cookie("user", user);userName.setMaxAge(30*60);response.addCookie(userName);response.sendRedirect("LoginSuccess.jsp");}else{RequestDispatcher rd = getServletContext().getRequestDispatcher("/login.html");PrintWriter out= response.getWriter();out.println("<font color=red>Either user name or password is wrong.</font>");rd.include(request, response);}}}

    When the client is authenticated, it’s forwarded to LoginSuccess.jsp

    LoginSuccess.jsp code:

    Notice that there is no session validation logic in the above JSP. It contains a link to another JSP page, CheckoutPage.jsp.

    CheckoutPage.jsp code:

    <%@ page language="java" contentType="text/html; charset=US-ASCII"pageEncoding="US-ASCII"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
    <title>Login Success Page</title>
    </head>
    <body>
    <%
    String userName = null;
    String sessionID = null;
    Cookie[] cookies = request.getCookies();
    if(cookies !=null){
    for(Cookie cookie : cookies){if(cookie.getName().equals("user")) userName = cookie.getValue();
    }
    }
    %>
    <h3>Hi <%=userName %>, do the checkout.</h3>
    <br>
    <form action="LogoutServlet" method="post">
    <input type="submit" value="Logout" >
    </form>
    </body>
    </html>

    LogoutServlet is invoked when a client clicks on the Logout button in any of the JSP pages.

    Now we will create logging and authentication servlet filter classes.

    package com.journaldev.servlet.filters;import java.io.IOException;
    import java.util.Enumeration;import javax.servlet.Filter;
    import javax.servlet.FilterChain;
    import javax.servlet.FilterConfig;
    import javax.servlet.ServletContext;
    import javax.servlet.ServletException;
    import javax.servlet.ServletRequest;
    import javax.servlet.ServletResponse;
    import javax.servlet.annotation.WebFilter;
    import javax.servlet.http.Cookie;
    import javax.servlet.http.HttpServletRequest;/*** Servlet Filter implementation class RequestLoggingFilter*/
    @WebFilter("/RequestLoggingFilter")
    public class RequestLoggingFilter implements Filter {private ServletContext context;public void init(FilterConfig fConfig) throws ServletException {this.context = fConfig.getServletContext();this.context.log("RequestLoggingFilter initialized");}public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {HttpServletRequest req = (HttpServletRequest) request;Enumeration<String> params = req.getParameterNames();while(params.hasMoreElements()){String name = params.nextElement();String value = request.getParameter(name);this.context.log(req.getRemoteAddr() + "::Request Params::{"+name+"="+value+"}");}Cookie[] cookies = req.getCookies();if(cookies != null){for(Cookie cookie : cookies){this.context.log(req.getRemoteAddr() + "::Cookie::{"+cookie.getName()+","+cookie.getValue()+"}");}}// pass the request along the filter chainchain.doFilter(request, response);}public void destroy() {//we can close resources here}}

    Notice that we are not authenticating any HTML page or LoginServlet. Now we will configure these filters mapping in the web.xml file.

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns="https://java.sun.com/xml/ns/javaee" xsi:schemaLocation="https://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"><display-name>ServletFilterExample</display-name><welcome-file-list><welcome-file>login.html</welcome-file></welcome-file-list><filter><filter-name>RequestLoggingFilter</filter-name><filter-class>com.journaldev.servlet.filters.RequestLoggingFilter</filter-class></filter><filter><filter-name>AuthenticationFilter</filter-name><filter-class>com.journaldev.servlet.filters.AuthenticationFilter</filter-class></filter><filter-mapping><filter-name>RequestLoggingFilter</filter-name><url-pattern>/*</url-pattern><dispatcher>REQUEST</dispatcher></filter-mapping><filter-mapping><filter-name>AuthenticationFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping>
    </web-app>

    Now when we will run our application, we will get response pages like below images.

    If you are not logged in and try to access any JSP page, you will be forwarded to the login page.

    In the server log file, you can see the logs written by servlet filters as well as servlets.

    Aug 13, 2013 1:06:07 AM org.apache.catalina.core.ApplicationContext log
    INFO: 0:0:0:0:0:0:0:1%0::Cookie::{JSESSIONID,B7275762B8D23121152B1270D6EB240A}
    Aug 13, 2013 1:06:07 AM org.apache.catalina.core.ApplicationContext log
    INFO: Requested Resource::/ServletFilterExample/
    Aug 13, 2013 1:06:07 AM org.apache.catalina.core.ApplicationContext log
    INFO: Unauthorized access request
    Aug 13, 2013 1:06:07 AM org.apache.catalina.core.ApplicationContext log
    INFO: 0:0:0:0:0:0:0:1%0::Cookie::{JSESSIONID,B7275762B8D23121152B1270D6EB240A}
    Aug 13, 2013 1:06:07 AM org.apache.catalina.core.ApplicationContext log
    INFO: Requested Resource::/ServletFilterExample/login.html
    Aug 13, 2013 1:06:43 AM org.apache.catalina.core.ApplicationContext log
    INFO: 0:0:0:0:0:0:0:1%0::Request Params::{pwd=password}
    Aug 13, 2013 1:06:43 AM org.apache.catalina.core.ApplicationContext log
    INFO: 0:0:0:0:0:0:0:1%0::Request Params::{user=admin}
    Aug 13, 2013 1:06:43 AM org.apache.catalina.core.ApplicationContext log
    INFO: 0:0:0:0:0:0:0:1%0::Cookie::{JSESSIONID,B7275762B8D23121152B1270D6EB240A}
    Aug 13, 2013 1:06:43 AM org.apache.catalina.core.ApplicationContext log
    INFO: Requested Resource::/ServletFilterExample/LoginServlet
    Aug 13, 2013 1:06:43 AM org.apache.catalina.core.ApplicationContext log
    INFO: 0:0:0:0:0:0:0:1%0::Cookie::{JSESSIONID,8BDF777933194EDCAC1D8F1B73633C56}
    Aug 13, 2013 1:06:43 AM org.apache.catalina.core.ApplicationContext log
    INFO: 0:0:0:0:0:0:0:1%0::Cookie::{user,admin}
    Aug 13, 2013 1:06:43 AM org.apache.catalina.core.ApplicationContext log
    INFO: Requested Resource::/ServletFilterExample/LoginSuccess.jsp
    Aug 13, 2013 1:06:52 AM org.apache.catalina.core.ApplicationContext log
    INFO: 0:0:0:0:0:0:0:1%0::Cookie::{JSESSIONID,8BDF777933194EDCAC1D8F1B73633C56}
    Aug 13, 2013 1:06:52 AM org.apache.catalina.core.ApplicationContext log
    INFO: 0:0:0:0:0:0:0:1%0::Cookie::{user,admin}
    Aug 13, 2013 1:06:52 AM org.apache.catalina.core.ApplicationContext log
    INFO: Requested Resource::/ServletFilterExample/CheckoutPage.jsp
    Aug 13, 2013 1:07:00 AM org.apache.catalina.core.ApplicationContext log
    INFO: 0:0:0:0:0:0:0:1%0::Cookie::{JSESSIONID,8BDF777933194EDCAC1D8F1B73633C56}
    Aug 13, 2013 1:07:00 AM org.apache.catalina.core.ApplicationContext log
    INFO: 0:0:0:0:0:0:0:1%0::Cookie::{user,admin}
    Aug 13, 2013 1:07:00 AM org.apache.catalina.core.ApplicationContext log
    INFO: Requested Resource::/ServletFilterExample/LogoutServlet
    JSESSIONID=8BDF777933194EDCAC1D8F1B73633C56
    User=Pankaj
    Aug 13, 2013 1:07:00 AM org.apache.catalina.core.ApplicationContext log
    INFO: 0:0:0:0:0:0:0:1%0::Cookie::{JSESSIONID,8BDF777933194EDCAC1D8F1B73633C56}
    Aug 13, 2013 1:07:00 AM org.apache.catalina.core.ApplicationContext log
    INFO: 0:0:0:0:0:0:0:1%0::Cookie::{user,admin}
    Aug 13, 2013 1:07:00 AM org.apache.catalina.core.ApplicationContext log
    INFO: Requested Resource::/ServletFilterExample/login.html
    Aug 13, 2013 1:07:06 AM org.apache.catalina.core.ApplicationContext log
    INFO: 0:0:0:0:0:0:0:1%0::Cookie::{JSESSIONID,8BDF777933194EDCAC1D8F1B73633C56}
    Aug 13, 2013 1:07:07 AM org.apache.catalina.core.ApplicationContext log
    INFO: 0:0:0:0:0:0:0:1%0::Cookie::{user,admin}
    Aug 13, 2013 1:07:07 AM org.apache.catalina.core.ApplicationContext log
    INFO: Requested Resource::/ServletFilterExample/LoginSuccess.jsp
    Aug 13, 2013 1:07:07 AM org.apache.catalina.core.ApplicationContext log
    INFO: Unauthorized access request
    Aug 13, 2013 1:07:07 AM org.apache.catalina.core.ApplicationContext log
    INFO: 0:0:0:0:0:0:0:1%0::Cookie::{JSESSIONID,8BDF777933194EDCAC1D8F1B73633C56}
    Aug 13, 2013 1:07:07 AM org.apache.catalina.core.ApplicationContext log
    INFO: 0:0:0:0:0:0:0:1%0::Cookie::{user,admin}
    Aug 13, 2013 1:07:07 AM org.apache.catalina.core.ApplicationContext log
    INFO: Requested Resource::/ServletFilterExample/login.html

    在我们的servlet过滤器示例中 ,我们将创建过滤器以记录请求cookie和参数,并验证到除静态HTML和LoginServlet之外的所有资源的会话,因为它们没有会话。

    我们将创建一个动态的Web项目ServletFilterExample,其项目结构如下图所示。

    login.html是我们应用程序的入口点,用户将在其中提供用于验证的登录ID和密码。

    login.html代码:

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="US-ASCII">
    <title>Login Page</title>
    </head>
    <body><form action="LoginServlet" method="post">Username: <input type="text" name="user">
    <br>
    Password: <input type="password" name="pwd">
    <br>
    <input type="submit" value="Login">
    </form>
    </body>
    </html>

    LoginServlet用于验证来自客户端的登录请求。

    客户端通过身份验证后,将转发到LoginSuccess.jsp

    LoginSuccess.jsp代码:

    <%@ page language="java" contentType="text/html; charset=US-ASCII"pageEncoding="US-ASCII"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
    <title>Login Success Page</title>
    </head>
    <body>
    <%
    //allow access only if session exists
    String user = (String) session.getAttribute("user");
    String userName = null;
    String sessionID = null;
    Cookie[] cookies = request.getCookies();
    if(cookies !=null){
    for(Cookie cookie : cookies){if(cookie.getName().equals("user")) userName = cookie.getValue();if(cookie.getName().equals("JSESSIONID")) sessionID = cookie.getValue();
    }
    }
    %>
    <h3>Hi <%=userName %>, Login successful. Your Session ID=<%=sessionID %></h3>
    <br>
    User=<%=user %>
    <br>
    <a href="CheckoutPage.jsp">Checkout Page</a>
    <form action="LogoutServlet" method="post">
    <input type="submit" value="Logout" >
    </form>
    </body>
    </html>

    请注意,上述JSP中没有会话验证逻辑。 它包含指向另一个JSP页面CheckoutPage.jsp的链接。

    CheckoutPage.jsp代码:

    当客户端单击任何JSP页面中的Logout按钮时,将调用LogoutServlet。

    package com.journaldev.servlet.session;import java.io.IOException;import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.Cookie;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;/*** Servlet implementation class LogoutServlet*/
    @WebServlet("/LogoutServlet")
    public class LogoutServlet extends HttpServlet {private static final long serialVersionUID = 1L;protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {response.setContentType("text/html");Cookie[] cookies = request.getCookies();if(cookies != null){for(Cookie cookie : cookies){if(cookie.getName().equals("JSESSIONID")){System.out.println("JSESSIONID="+cookie.getValue());break;}}}//invalidate the session if existsHttpSession session = request.getSession(false);System.out.println("User="+session.getAttribute("user"));if(session != null){session.invalidate();}response.sendRedirect("login.html");}}

    现在,我们将创建日志记录和身份验证servlet过滤器类。

    package com.journaldev.servlet.filters;import java.io.IOException;import javax.servlet.Filter;
    import javax.servlet.FilterChain;
    import javax.servlet.FilterConfig;
    import javax.servlet.ServletContext;
    import javax.servlet.ServletException;
    import javax.servlet.ServletRequest;
    import javax.servlet.ServletResponse;
    import javax.servlet.annotation.WebFilter;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;@WebFilter("/AuthenticationFilter")
    public class AuthenticationFilter implements Filter {private ServletContext context;public void init(FilterConfig fConfig) throws ServletException {this.context = fConfig.getServletContext();this.context.log("AuthenticationFilter initialized");}public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {HttpServletRequest req = (HttpServletRequest) request;HttpServletResponse res = (HttpServletResponse) response;String uri = req.getRequestURI();this.context.log("Requested Resource::"+uri);HttpSession session = req.getSession(false);if(session == null && !(uri.endsWith("html") || uri.endsWith("LoginServlet"))){this.context.log("Unauthorized access request");res.sendRedirect("login.html");}else{// pass the request along the filter chainchain.doFilter(request, response);}}public void destroy() {//close any resources here}}

    请注意,我们没有认证任何HTML页面或LoginServlet。 现在,我们将在web.xml文件中配置这些过滤器映射。

    现在,当我们运行我们的应用程序时,我们将获得如下图所示的响应页面。

    如果您尚未登录并尝试访问任何JSP页面,那么您将被转发到登录页面。

    在服务器日志文件中,您可以看到servlet过滤器以及servlet编写的日志。

That’s all for Servlet Filter in java. It’s one of the important features of Java EE web application and we should use it for common tasks performed by various servlets. In future posts, we will look into servlet listeners and cookies.

这就是Java中的Servlet过滤器的全部内容。 它是Java EE Web应用程序的重要功能之一,我们应该将其用于各种servlet执行的常见任务。 在以后的文章中,我们将研究servlet侦听器和cookie。

Update: After getting a lot of requests for the downloadable project, I have attached it to the post, download it from the link below.

更新:在收到大量可下载项目的请求后,我将其附加到帖子中,可从下面的链接下载。

Download Servlet Filter Example Project下载Servlet筛选器示例项目

Check out next article in the series about Servlet Listener.

查阅有关Servlet Listener的系列中的下一篇文章。

Update

更新资料

Struts 2 uses Servlet Filter to intercept the client requests and forward them to appropriate action classes, these are called Struts 2 Interceptors. Check out Struts 2 Beginners Tutorial.

Struts 2使用Servlet筛选器来拦截客户端请求,并将其转发到适当的操作类,这些类称为Struts 2拦截器。 查看Struts 2初学者教程

翻译自: https://www.journaldev.com/1933/java-servlet-filter-example-tutorial

servlet过滤器 实例

servlet过滤器 实例_Java Servlet过滤器示例教程相关推荐

  1. java ldap操作实例_Java Spring Security示例教程中的2种设置LDAP Active Directory身份验证的方法...

    java ldap操作实例 LDAP身份验证是世界上最流行的企业应用程序身份验证机制之一,而Active Directory (Microsoft为Windows提供的LDAP实现)是另一种广泛使用的 ...

  2. java项目使用过滤器实例_Java web开发--过滤器篇(详细介绍)

    一. web过滤器的介绍 1.过滤器 在生活中,过滤这种我们时常可见:比如水资源的处理,化学药剂的提取等等.所谓过滤,就是指对某事物的处理进行一定的处理获取相应的结果的一个过程.它可以总结为下: 过滤 ...

  3. 自定义标签的使用jsp实例_JSP自定义标签示例教程

    自定义标签的使用jsp实例 Today we will look into JSP custom tags. Earlier we learned about JSP Action Elements, ...

  4. jsf入门实例_JSF错误消息示例教程

    jsf入门实例 In this section, we will see how to use the default JSF validators to shoot out the built in ...

  5. java memcache 实例_Java使用memcache示例

    许多Web应用都将数据保存到RDBMS中,应用服务器从中读取数据并在浏览器中显示. 但随着数据量的增大.访问的集中,就会出现RDBMS的负担加重.数据库响应恶化. 网站显示延迟等重大影响. 这时就该m ...

  6. java quartz实例_Java任务调度框架Quartz教程实例

    介绍 Quartz is a full-featured, open source job scheduling service that can be integrated with, or use ...

  7. java过滤器原理,拦截器,过滤器,监听器 区别及执行顺序

    本文引用该作者(花开半夏)著作内容,觉得写的很好,记录一下便于回看防止失踪,更多详情请查看原作者. 同时还搜罗了其他便于理解的博文感兴趣的可以看看促进理解 拦截器,过滤器,监听器执行顺序(被拦截个人过 ...

  8. 【Servlet】Filter过滤器详解、使用示例

    Filter过滤器讲解 定义 过滤器处于浏览器与servlet之间,是一个实现了 javax.servlet.Filter 接口的 Java 类 客户端发送的请求.服务器发送的资源,需要通过过滤器,才 ...

  9. angularjs 实例_AngularJS过滤器示例教程

    angularjs 实例 We looked at View Model, View and Controller concepts in the previous post. Now we are ...

最新文章

  1. 如何在一个文件中写多个Vue组件(译-有删改)
  2. 【白话机器学习】算法理论+实战之Xgboost算法
  3. c语言点按钮弹窗口,【iOS】按钮点击弹窗
  4. 经典解释监视器和对象锁
  5. linux+npm+v+报错_linux下安装npm
  6. win7右键菜单不见解决办法
  7. HttpClient、HttpURLConnection、OKHttp和Volley
  8. bootstrap 预定义样式风格
  9. NVIDIA驱动版本、Pytorch版本、Cuda版本三者之间对应的版本关系
  10. android按键录制,按键录制(FRep Finger Replayer)
  11. 大淘客的index.php,index.php · zenozhengs/大淘客CMS底部菜单修改版 - Gitee.com
  12. maya安装步骤 新手安装软件基础教程(附安装包)
  13. ESXI下安装OpenWrt/LEDE软路由教程(附超全功能固件镜像下载)
  14. 首次曝光:大厂都是这样过1024的,看的我酸了
  15. Galaxy S4 GT-I9500如何root 安卓5.0.1
  16. 靓丽图像中的一抹——摩尔纹
  17. 从线性空间到再生核希尔伯特空间(RKHS)
  18. 用word写毕业论文时当未正常保存文件时,重新打开时,封面格式混乱的解决方法
  19. php 做支付宝电脑网站和app支付
  20. 第44章 通过GoogleAuthenticator插件执行登录操作

热门文章

  1. 【JQuery NoviceToNinja系列】目录
  2. Hacker News的全文输出RSS地址
  3. 连接Oracle9i,因字符集造成乱码的解决方法
  4. MyEclipse7.0及JDK1.6.0的安装及配置过程(修改)
  5. [转载] 深层复制构造函数和浅层复制构造函数区别
  6. [转载] Java中自定义异常的声明与处理
  7. Django之form组件加cookie,session
  8. 正式版的Linux Kernel 5.1来了,非LTS
  9. python - Flask 基础(1)
  10. POJ3764 The xor-longest Path(字典树)