Hai filter A và B được khai báo trong web.xml theo thứ tự A rồi B, cả hai map /*. Servlet in ra S. Request tới servlet sẽ in ra gì?
public class A implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
System.out.print("A1 ");
chain.doFilter(req, res);
System.out.print("A2 ");
}
}
// B giống hệt A nhưng in "B1 " và "B2 "
Xem đáp án và giải thích
Mỗi filter bọc phần còn lại của chain: code trước chain.doFilter là tiền xử lý, code sau là hậu xử lý. Vì lời gọi lồng nhau nên hậu xử lý chạy theo thứ tự ngược với tiền xử lý. Đây chính là mẫu Chain of Responsibility, thường dùng để đo thời gian xử lý hay ghi log response.