View Javadoc

1   /**
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * 
4    * Copyright (C) 1999-2006, QOS.ch
5    * 
6    * This library is free software, you can redistribute it and/or modify it under
7    * the terms of the GNU Lesser General Public License as published by the Free
8    * Software Foundation.
9    */
10  
11  package chapter7;
12  
13  import java.io.IOException;
14  import java.security.Principal;
15  
16  import javax.servlet.Filter;
17  import javax.servlet.FilterChain;
18  import javax.servlet.FilterConfig;
19  import javax.servlet.ServletException;
20  import javax.servlet.ServletRequest;
21  import javax.servlet.ServletResponse;
22  import javax.servlet.http.HttpServletRequest;
23  import javax.servlet.http.HttpSession;
24  
25  import org.slf4j.MDC;
26  
27  /**
28   * A simple servlet filter that puts the username
29   * found either in the Principle or as a session attribute
30   * in the MDC.
31   * 
32   * The value is removed from the MDC once the request has been
33   * fully processed.
34   *
35   * To be used, add the following lines to a web.xml file
36   * 
37   * <filter>
38   *   <filter-name>User Servlet Filter</filter-name>
39   *   <filter-class>
40   *     chapter7.UserServletFilter
41   *   </filter-class>
42   * </filter>
43   * <filter-mapping>
44   *   <filter-name>User Servlet Filter</filter-name>
45   *   <url-pattern>/*</url-pattern>
46   * </filter-mapping>
47   *
48   * @author S&eacute;bastien Pennec
49   */
50  public class UserServletFilter implements Filter {
51  
52    boolean userRegistered = false;
53    
54    private final String userKey = "username";
55    
56    public void destroy() {
57    }
58  
59    public void doFilter(ServletRequest request, ServletResponse response,
60        FilterChain chain) throws IOException, ServletException {
61  
62      HttpServletRequest req = (HttpServletRequest) request;
63      Principal principal = req.getUserPrincipal();
64  
65      if (principal != null) {
66        String username = principal.getName();
67        registerUsername(username);
68      } else {
69        HttpSession session = req.getSession();
70        String username = (String)session.getAttribute(userKey);
71        registerUsername(username);
72      }
73      
74      try {
75        chain.doFilter(request, response);
76      } finally {
77        if (userRegistered) {
78          MDC.remove(userKey);
79        }
80      }
81    }
82  
83    public void init(FilterConfig arg0) throws ServletException {
84    }
85    
86    private void registerUsername(String username) {
87      if (username != null && username.trim().length() > 0) {
88        MDC.put(userKey, username);
89        userRegistered = true;
90      }
91    }
92  
93  }