Tomcat filter generates duplicate localhost.log lines

纵饮孤独 提交于 2020-03-26 08:22:51

问题


This code, most of which I inherited, runs fine except System.out.println("Success") generates a lot (7-37, random) of identical lines in localhost.log instead of just one when it runs:

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

What's going on??

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.");
    }
}

}


回答1:


With log4j, I've encountered duplicate log messages when I assign overlapping paths to an appender. For example

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




回答2:


You didn't supply the URL mapping for this filter, but I suspect that it's mapped to other elements in the generated HTML.

For example, if a page contains 5 images and 2 CSS files the client would make 7 additional HTTP requests after it parses the generated HTML for a single page request. In this case I would expect to see 8 SUCCESS lines printed.

You can always see the path for each request by printing httpRequest.getRequestURL()




回答3:


You have multiple logger attached to the same class. Just disable your root logger. That is the problem with duplicate log statements most of the time. cheers



来源:https://stackoverflow.com/questions/5157615/tomcat-filter-generates-duplicate-localhost-log-lines

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!