CÔNG NGHỆ THÔNG TIN >> BÀI VIẾT CHỌN LỌC

[Java Web] Tìm hiểu về Filter trong JSP Servlet

Đăng lúc: 08:02 AM - 31/01/2024 bởi Charles Chung - 1109

Trong bài này chúng ta sẽ tìm hiểu về Filter trong JSP Servlet

Giới thiệu

Filter là một đối tượng được gọi trong quá trình tiền xử lý vàhậu xử lý của một request. Nó chủ yếu được sử dụng để thực hiện các tác vụ filter như chuyển đổi, ghi nhật ký, nén, mã hóa và giải mã, xác thực đầu vào, v.v. Filter servlet có thể được sử dụng thông qua việc khai báo trong tệp web.xml, và nếu không muốn chúng ta có thể xóa khai báo trong web.xml, filter sẽ tự động không áp dụng. Vì vậy chi phí bảo trì sẽ ít hơn.

Một số tác vụ phổ biến mà chúng ta có thể thực hiện với bộ lọc servlet là:

  • Ghi nhật ký các tham số yêu cầu vào tệp nhật ký.
  • Nhận diện người dùng và xác thực yêu cầu tài nguyên.
  • Định dạng nội dung hoặc tiêu đề yêu cầu trước khi gửi nó đến servlet.
  • Nén dữ liệu phản hồi gửi cho khách hàng.
  • Thay đổi phản hồi bằng cách thêm một số cookie, thông tin tiêu đề, v.v.

Filter Servlet Interface: tương tự như Servlet Interface và chúng ta cần triển khai nó để tạo filter servlet của riêng mình. Filter Servlet Interface chứa các phương thức vòng đời của Filter và được quản lý bởi Servlet Container. Các phương thức vòng đời của Filter Servlet Interface bao gồm:

  • void init(FilterConfig paramFilterConfig) - Đây là phương thức khởi tạo Filter. Phương thức này chỉ được gọi một lần trong vòng đời của Filter và chúng ta nên khởi tạo bất kỳ tài nguyên nào trong phương thức này.
  • doFilter(ServletRequest paramServletRequest, ServletResponse paramServletResponse, FilterChain paramFilterChain) - Đây là phương thức được gọi mỗi khi nó phải áp dụng filter cho tài nguyên cụ thể.
  • void destroy() - phương thức destroy() khi filter kết thúc. Đây là phương pháp mà chúng ta có thể đóng mọi tài nguyên được mở bằng filter. Phương thức này chỉ được gọi một lần trong vòng đời của bộ lọc.

Servlet WebFilter annotation

javax.servlet.annotation.WebFilter được giới thiệu trong Servlet 3.0 và chúng ta có thể sử dụng annotation này để khai báo Filter Servlet. Chúng ta có thể sử dụng annotation này để xác định các tham số init, tên và mô tả filter, servlet, mẫu url và loại bộ điều phối để áp dụng filter. Nếu bạn thường xuyên thay đổi cấu hình filter, tốt hơn nên sử dụng web.xml vì điều đó sẽ không yêu cầu bạn biên dịch lại lớp filter.

Servlet Filter configuration in web.xml

Chúng ta khai báo filter trong web.xml như bên đưới

1
2
3
4
5
6
7
8
<filter>
  <filter-name>AuthenticateFilter</filter-name> <!-- mandatory -->
  <filter-class>com.hanam88.filters.AuthenticateFilter</filter-class> <!-- mandatory -->
  <init-param> <!-- optional -->
  <param-name>test</param-name>
  <param-value>testValue</param-value>
  </init-param>
</filter>

Tiếp theo chúng ta có thể map filter tới một Servlet hoặc một mẫu url-pattern như sau

1
2
3
4
5
6
<filter-mapping>
  <filter-name>AuthenticateFilter</filter-name> <!-- mandatory -->
  <url-pattern>/*</url-pattern> <!-- either url-pattern or servlet-name is mandatory -->
  <servlet-name>LoginServlet</servlet-name>
  <dispatcher>REQUEST</dispatcher>
</filter-mapping>

Ví dụ:

AuthenticateFilter sẽ xác thực người dùng, nếu người dùng đã login thì cho phép vào trang index.jsp và các trang con, ngược lại sẽ yêu cầu người dùng login.

Bước 1: Tạo project Dynamic Web Project với tên "JSPServletSession04"

Bước 2: Tạo cấu trúc các trang, Servlets, Filters như bên dưới

Bước 3: Code cho các trang jsp, servlet, filter theo gợi ý sau

- index.jsp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Tìm hiểu về Filter trong JSP and Servlet</title>
<style>
#nav {
	width: 1200px;
	margin: auto;
	height: 30px;
}

#content {
	width: 1200px;
	margin: auto;
	height: 500px;
	background-color: gray;
	color: white;
	padding: 20px;
}
</style>
</head>
<body>
	<div id="nav">
		<a href="index.jsp">Trang chủ </a> | <a href="index.jsp?page=product">Quản lý sản phẩm </a> | <a href="index.jsp?page=about">Giới thiệu </a>
		<%
		if (session.getAttribute("user") != null) {
		%>
		Xin chào:${sessionScope.user} <a href="LogoutServlet"> Thoát</a>
		<%
		}
		%>
	</div>
	<div id="content">
		<%
		if (request.getParameter("page") != null) {
		%>
		<jsp:include page="${param.page}.jsp"></jsp:include>
		<%
		} else {
		%>
		<h2>Trang chủ</h2>
		<%
		}
		%>
	</div>
</body>
</html>

- login.jsp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Đăng nhập</title>
</head>
<body>
	<h1>Đăng nhập</h1>
	<span style="color: red">${msg}</span>
	<form action="LoginServlet" method="post">
		<table>
			<tr>
				<td>Tên đăng nhập</td>
				<td><input type="text" name="username"/></td>
			</tr>
			<tr>
				<td>Mật khẩu</td>
				<td><input type="password" name="password"/></td>
			</tr>
			<tr>
				<td colspan="2"><button>Đăng nhập</button></td>
			</tr>
		</table>
	</form>

</body>
</html>

- about.jsp

1
2
3
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<h2>Tìm hiểu về Filter trong JSP and Servlet</h2>

- product.jsp

1
2
3
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<h1>Trang sản phẩm</h1>

- LoginServlet.java

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
String user="hanam88";
String pass="123456";
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// get request parameters for userID and password
				String username = request.getParameter("username");
				String password = request.getParameter("password");
				if(username.equals(user) && password.equals(pass)){
					HttpSession session = request.getSession();
					session.setAttribute("user", user);
					//setting session to expiry in 30 mins
					session.setMaxInactiveInterval(30*60);
					Cookie userName = new Cookie("user", user);
					userName.setMaxAge(30*60);
					response.addCookie(userName);
					response.sendRedirect("index.jsp");
				}else{
					request.setAttribute("msg", "Đăng nhập sai");
					request.getRequestDispatcher("login.jsp").forward(request, response);
				}
}

- LogoutServlet.java

1
2
3
4
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.getSession().invalidate();
		response.sendRedirect("login.jsp");
}

- AuthenticateFilter.java

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import java.io.IOException;
import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet Filter implementation class AuthenticateFilter
 */
@WebFilter(dispatcherTypes = {DispatcherType.REQUEST }
					, urlPatterns = { "/*" })
public class AuthenticateFilter extends HttpFilter implements Filter {
       
    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/**
     * @see HttpFilter#HttpFilter()
     */
    public AuthenticateFilter() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
		String uri=req.getRequestURI();
		HttpSession session = req.getSession();
		if((session==null || session.getAttribute("user")==null) &&  !(uri.contains("login.jsp") || uri.contains("LoginServlet")))
		{
			res.sendRedirect("login.jsp");
		}
		// pass the request along the filter chain
		chain.doFilter(request, response);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}

Bước 4: Run App và xem kết quả

Link tải source code

Video demo

thay lời cảm ơn!

QUẢNG CÁO - TIẾP THỊ