Filters เป็น Java classes ที่ใช้ใน Servlet/JSP เพื่อ:
- Intercept request จาก client ก่อนถึง resource (pre-processing)
- Manipulate response จาก server ก่อนส่งกลับ client (post-processing)
ประเภท Filters ที่นิยม
- Authentication Filters - ตรวจสอบสิทธิ์การเข้าถึง
- Logging / Auditing Filters - บันทึก log request/response
- Data Compression Filters - บีบอัดข้อมูล (GZIP)
- Encryption Filters - เข้ารหัส/ถอดรหัสข้อมูล
- Character Encoding Filters - ตั้งค่า charset (UTF-8)
- CORS Filters - จัดการ Cross-Origin Resource Sharing
- XSL/T Filters - Transform XML content
- Image Conversion Filters - แปลงรูปภาพ on-the-fly
การ Deploy
- สร้าง class implement
javax.servlet.Filter - กำหนดใน web.xml (deployment descriptor)
- map กับ servlet/JSP name หรือ URL pattern
web.xml อยู่ที่ <Tomcat>/conf/web.xml (global) หรือ WEB-INF/web.xml (per webapp)
วงจรชีวิต (Lifecycle)
init(FilterConfig)- เริ่มต้นครั้งเดียวตอน deploydoFilter(request, response, chain)- ทุก request ที่ match mappingdestroy()- ทอน deployed/undeployed
Filter Chain
หลาย filters สร้าง chain เรียงตามลำดับใน web.xml chain.doFilter() ส่งต่อไป filter ถัดไป จนถึง target resource แล้วคืนกลับมาถอยหลัง
ข้อดีของ Filters
- แยก cross-cutting concerns (logging, auth, encoding) ออกจาก business logic
- ใช้ซ้ำได้หลาย webapps
- เปลี่ยนแปลงได้โดยไม่แก้โค้ด JSP/Servlet
- Deploy แบบ declarative ใน web.xml