1
2
3
4
5
6
7
8
9
10
11
12
13
14 package chapters.mdc;
15
16 import java.io.IOException;
17 import java.security.Principal;
18
19 import jakarta.servlet.Filter;
20 import jakarta.servlet.FilterChain;
21 import jakarta.servlet.FilterConfig;
22 import jakarta.servlet.ServletException;
23 import jakarta.servlet.ServletRequest;
24 import jakarta.servlet.ServletResponse;
25 import jakarta.servlet.http.HttpServletRequest;
26
27 import org.slf4j.MDC;
28
29
30
31
32
33
34
35
36
37
38 public class UserServletFilter implements Filter {
39
40 private final String USER_KEY = "username";
41
42 public void destroy() {
43 }
44
45 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
46
47 boolean successfulRegistration = false;
48 HttpServletRequest req = (HttpServletRequest) request;
49 Principal principal = req.getUserPrincipal();
50
51
52
53 if (principal != null) {
54 String username = principal.getName();
55 successfulRegistration = registerUsername(username);
56 }
57
58 try {
59 chain.doFilter(request, response);
60 } finally {
61 if (successfulRegistration) {
62 MDC.remove(USER_KEY);
63 }
64 }
65 }
66
67 public void init(FilterConfig arg0) throws ServletException {
68 }
69
70
71
72
73
74
75
76 private boolean registerUsername(String username) {
77 if (username != null && username.trim().length() > 0) {
78 MDC.put(USER_KEY, username);
79 return true;
80 }
81 return false;
82 }
83
84 }