001/** 002 * Logback: the reliable, generic, fast and flexible logging framework. 003 * Copyright (C) 1999-2015, QOS.ch. All rights reserved. 004 * 005 * This program and the accompanying materials are dual-licensed under 006 * either the terms of the Eclipse Public License v1.0 as published by 007 * the Eclipse Foundation 008 * 009 * or (per the licensee's choosing) 010 * 011 * under the terms of the GNU Lesser General Public License version 2.1 012 * as published by the Free Software Foundation. 013 */ 014package chapters.mdc; 015 016import java.io.IOException; 017import java.security.Principal; 018 019import javax.servlet.Filter; 020import javax.servlet.FilterChain; 021import javax.servlet.FilterConfig; 022import javax.servlet.ServletException; 023import javax.servlet.ServletRequest; 024import javax.servlet.ServletResponse; 025import javax.servlet.http.HttpServletRequest; 026 027import org.slf4j.MDC; 028 029/** 030 * A simple servlet filter that puts the username 031 * found either in the Principal. 032 * 033 * <p> The value is removed from the MDC once the request has been 034 * fully processed. 035 * 036 * @author Sébastien Pennec 037 */ 038public class UserServletFilter implements Filter { 039 040 private final String USER_KEY = "username"; 041 042 public void destroy() { 043 } 044 045 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { 046 047 boolean successfulRegistration = false; 048 HttpServletRequest req = (HttpServletRequest) request; 049 Principal principal = req.getUserPrincipal(); 050 // Please note that we also could have used a cookie to 051 // retrieve the user name 052 053 if (principal != null) { 054 String username = principal.getName(); 055 successfulRegistration = registerUsername(username); 056 } 057 058 try { 059 chain.doFilter(request, response); 060 } finally { 061 if (successfulRegistration) { 062 MDC.remove(USER_KEY); 063 } 064 } 065 } 066 067 public void init(FilterConfig arg0) throws ServletException { 068 } 069 070 /** 071 * Register the user in the MDC under USER_KEY. 072 * 073 * @param username 074 * @return true id the user can be successfully registered 075 */ 076 private boolean registerUsername(String username) { 077 if (username != null && username.trim().length() > 0) { 078 MDC.put(USER_KEY, username); 079 return true; 080 } 081 return false; 082 } 083 084}