路径跟踪过滤器

import java.io.IOException;

import java.util.Enumeration;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

public class PathFilter implements Filter {
    public void destroy() {}

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest request     = (HttpServletRequest) request;
        String             path  = request.getRequestURI();
        Enumeration        e     = request.getParameterNames();
        StringBuffer       param = new StringBuffer();

        param.append("?");

        while (e.hasMoreElements()) {
            String name = (String) e.nextElement();

            param.append(name);

            String value = (String) request.getParameter(name);

            param.append("=" + value + "&");
        }

        param.deleteCharAt(param.length() - 1);

        HttpSession s       = request.getSession();
        String      curpath = (String) s.getAttribute("curpath");

        if (curpath == null) {
            s.setAttribute("curpath", path + param.toString());
        } else {
            if (!curpath.substring(0, (curpath.indexOf("?") == -1)
                                      ? curpath.length()
                                      : curpath.indexOf("?")).equals(path)) {
                s.setAttribute("lastpath", curpath);
                s.setAttribute("curpath", path + param.toString());
            }
        }

        chain.doFilter(request, response);
    }

    public void init(FilterConfig arg0) throws ServletException {}
}
成长的乐趣,在于分享!
大龄程序员,一路走来,感慨颇多。闲暇时写写字,希望能给同行人一点帮助。
本文版权归作者growithus和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
原文地址:https://www.cnblogs.com/growithus/p/11012593.html