1   package ch.qos.logback.demo;
2   
3   import java.io.IOException;
4   import java.security.Principal;
5   
6   import javax.servlet.Filter;
7   import javax.servlet.FilterChain;
8   import javax.servlet.FilterConfig;
9   import javax.servlet.ServletException;
10  import javax.servlet.ServletRequest;
11  import javax.servlet.ServletResponse;
12  import javax.servlet.http.HttpServletRequest;
13  import javax.servlet.http.HttpSession;
14  
15  import org.slf4j.MDC;
16  
17  public class UserServletFilter implements Filter {
18  
19    boolean userRegistered = false;
20  
21    public void destroy() {
22    }
23  
24    public void doFilter(ServletRequest request, ServletResponse response,
25  
26    FilterChain chain) throws IOException, ServletException {
27  
28      HttpServletRequest req = (HttpServletRequest) request;
29      Principal principal = req.getUserPrincipal();
30      // Please note that we could have also used a cookie to
31      // retreive the user name
32  
33      if (principal != null) {
34        String username = principal.getName();
35        registerUsername(username);
36      } else {
37        HttpSession session = req.getSession();
38        String value = (String) session
39            .getAttribute(Constants.USERID_SESSION_KEY);
40        registerUsername(value);
41      }
42  
43      try {
44        chain.doFilter(request, response);
45      } finally {
46        if (userRegistered) {
47          MDC.remove(Constants.USERID_MDC_KEY);
48        }
49      }
50    }
51  
52    public void init(FilterConfig arg0) throws ServletException {
53    }
54  
55    private void registerUsername(String value) {
56      System.out.println("in registerUsername "+Constants.USERID_MDC_KEY+"="+value);
57      if (value != null && value.trim().length() > 0) {
58        MDC.put(Constants.USERID_MDC_KEY, value);
59        userRegistered = true;
60      }
61    }
62  
63  }