支持自定义扩展名或空扩展名的Dispatcher

支持自定义类似于".do", ".php", ".aspx"这样的扩展名, 或者不使用扩展名. 在不使用扩展名的情况下, 所有被识别为action的链接, 最后一个foward slash后不能再出现"."号, 以免和常用的mime types混淆.

public class Dispatcher implements Filter {

    private static Logger logger = Logger.getLogger(Dispatcher.class);
    private String attribute = null;
    private FilterConfig filterConfig = null;
    private static String ext =SimpleConfig.getConfig("extension");

    // Initialise the dispatcher filter rule
    private static String regex;
    static
    {
        if (ext==null || ext.length() == 0 || ext.length() == 1)
        {
            ext = "";
            regex = ".*?/[^\\.]*?$";
        }
        else
        {
            if (ext.charAt(0)!='.') {ext = "."+ext;}
            regex = ".*?\\."+ ext.substring(1) + "$";
        }
    }

    public void init(FilterConfig filterConfig) throws ServletException
    {
        this.filterConfig = filterConfig;
        this.attribute = filterConfig.getInitParameter("attribute");
    }

    public void destroy()
    {
        this.attribute = null;
        this.filterConfig = null;
    }

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException
    {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        String servletPath = request.getServletPath();

        if (servletPath.matches(regex))
        {
            long startTime = System.currentTimeMillis();

            String name = servletPath.substring(1, servletPath.length() - ext.length()).replaceAll("/", ".");

            ActionContext context = SimpleConfig.getActionContext(name);

            if (context != null)
            {
                ActionContainer container = new ActionContainer(context, request, response);
                container.process();
            }
            long stopTime = System.currentTimeMillis();
            logger.info( "Dispatcher: " + servletPath + ": " + (stopTime - startTime) + " milliseconds");
        }
        else
        {
            chain.doFilter(req, res);
        }
    }

}

posted on 2011-10-26 22:08  Milton  阅读(328)  评论(0编辑  收藏  举报

导航