Tomcat过滤器生成重复的localhost.log行

时间:2011-03-01 16:53:10

标签: java tomcat servlet-filters

此代码(我继承了大部分代码)运行正常,除了 System.out.println(“Success”)在localhost.log中生成了很多(7-37,随机)相同的行当它运行时只有一个:

Mar 1, 2011 8:49:47 AM org.apache.catalina.core.StandardWrapperValve invoke
Success
Mar 1, 2011 8:49:47 AM org.apache.catalina.core.StandardWrapperValve invoke
Success
Mar 1, 2011 8:49:47 AM org.apache.catalina.core.StandardWrapperValve invoke
Success

发生了什么事?

public class SpecialFilter implements Filter {
public void doFilter(ServletRequest request, ServletResponse response, FilterChain fc)
        throws IOException, ServletException {
    if (request instanceof HttpServletRequest) {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String mainID = httpRequest.getRemoteUser();
        String username = "";
        try {
            Cookie c[] = httpRequest.getCookies();
            if (c == null) {
                username = getID(mainID);  // method omitted, just executes a SQL query
            } else {
                boolean cookieFound = false;
                for (int i = 0; i < c.length; i++) {
                    if (c[i].getName().equals("mainCookie")) {
                        username = c[i].getValue();
                        cookieFound = true;
                        break;
                    }
                }
                if (cookieFound) {
                    System.out.println("Success");
                } else {
                    username = getID(mainID);
                }
            }
        } catch (SQLException e) {
            System.out.println("Error 1 " + e);
            throw new ServletException(error, e);
        }
        AuthRequestWrapper wrapper = new AuthRequestWrapper(httpRequest, username);
        fc.doFilter(wrapper, response);
    }
    else {
        throw new RuntimeException("request is not a valid httpRequest object.");
    }
}

}

3 个答案:

答案 0 :(得分:0)

使用log4j,当我将重叠路径分配给appender时,我遇到了重复的日志消息。例如

com.blah.blam = appendThis
  com.blah = appendThis

答案 1 :(得分:0)

您没有为此过滤器提供URL映射,但我怀疑它已映射到生成的HTML中的其他元素。

例如,如果一个页面包含5个图像和2个CSS文件,则客户端在解析生成的HTML以获取单个页面请求后,将发出7个额外的HTTP请求。在这种情况下,我希望看到8条SUCCESS行打印出来。

您始终可以通过打印httpRequest.getRequestURL()

查看每个请求的路径

答案 2 :(得分:0)

您有多个记录器连接到同一个类。只需禁用根记录器即可。这是大多数时候重复日志语句的问题。 欢呼声