Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม

จะใช้ตัวกรองใน JSP ได้อย่างไร?


ตัวอย่างต่อไปนี้แสดงวิธีการพิมพ์ที่อยู่ IP ของไคลเอ็นต์และวันที่ เวลาปัจจุบัน ทุกครั้งที่เข้าถึงไฟล์ JSP ตัวอย่างนี้จะช่วยให้คุณเข้าใจพื้นฐานของตัวกรอง 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 . ของคุณ ไฟล์ใน /webapps/ROOT/WEB-INF/classes .

การแมปตัวกรอง JSP ใน Web.xml

มีการกำหนดตัวกรองแล้วจับคู่กับ URL หรือชื่อไฟล์ JSP ในลักษณะเดียวกับที่กำหนด Servlet จากนั้นจึงจับคู่กับรูปแบบ URL ใน web.xml ไฟล์. สร้างรายการต่อไปนี้สำหรับแท็กตัวกรองในไฟล์อธิบายการนำไปใช้งาน 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>

ตัวกรองด้านบนจะนำไปใช้กับเซิร์ฟเล็ตและ JSP ทั้งหมดเนื่องจากเราระบุ /* ในการกำหนดค่าของเรา คุณสามารถระบุเซิร์ฟเล็ตเฉพาะหรือพาธ JSP หากคุณต้องการใช้ตัวกรองกับเซิร์ฟเล็ตบางตัวหรือ JSP เท่านั้น

ตอนนี้ลองเรียกเซิร์ฟเล็ตหรือ JSP แล้วคุณจะเห็นบันทึกที่สร้างขึ้นในบันทึกของเว็บเซิร์ฟเวอร์ของคุณ คุณสามารถใช้ ตัวบันทึก Log4J เพื่อเข้าสู่ระบบด้านบนให้เข้าสู่ระบบในไฟล์แยกต่างหาก