如何在JSP中使用過濾器?


以下示例演示瞭如何每次訪問任何JSP檔案時都列印客戶端的IP地址和當前日期時間。此示例將為您提供對JSP過濾器的基本瞭解,但您可以使用相同的概念編寫更復雜的過濾器應用程式:

// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;

// Implements Filter class
public class LogFilter implements Filter {
   public void init(FilterConfig config) throws ServletException {
      // Get init parameter
      String testParam = config.getInitParameter("test-param");
      //Print the init parameter
      System.out.println("Test Param: " + testParam);
   }
   public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
   throws java.io.IOException, ServletException {

      // Get the IP address of client machine.
      String ipAddress = request.getRemoteAddr();
      // Log the IP address and current timestamp.
      System.out.println("IP "+ ipAddress + ", Time "+ new Date().toString());
      // Pass request back down the filter chain
      chain.doFilter(request,response);
   }
   public void destroy( ) {
      /* Called before the Filter instance is removed
      from service by the web container*/
   }
}

以通常的方式編譯**LogFilter.java**並將您的**LogFilter.class**檔案放入**<Tomcat安裝目錄>/webapps/ROOT/WEB-INF/classes**。

JSP過濾器對映在web.xml中

過濾器被定義,然後對映到URL或JSP檔名,這與Servlet定義並對映到**web.xml**檔案中的URL模式的方式非常相似。在部署描述符檔案**web.xml**中建立以下過濾器標籤條目:

<filter>
   <filter-name>LogFilter</filter-name>
   <filter-class>LogFilter</filter-class>
   <init-param>
      <param-name>test-param</param-name>
      <param-value>Initialization Paramter</param-value>
      </init-param>
</filter>
<filter-mapping>
   <filter-name>LogFilter</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping>

由於我們在配置中指定了**/***,因此上述過濾器將應用於所有servlet和JSP。如果您只想將過濾器應用於少數servlet或JSP,則可以指定特定的servlet或JSP路徑。

現在嘗試呼叫任何servlet或JSP,您將在Web伺服器日誌中看到生成的日誌。您可以使用**Log4J記錄器**將上述日誌記錄到單獨的檔案中。

更新於:2019年7月30日

561 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告