26、Eternal框架v2-框架设计 前置分发器 1、代码

package cn.eternal.web;

import cn.eternal.web.core.Dispatcher;
import cn.eternal.web.core.DispatcherLoader;
import cn.eternal.web.core.RestHttp;
import cn.eternal.web.core.RestUrl;
import cn.eternal.web.http.RestRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicBoolean;

public class DispatcherFilter implements Filter {

    private final Log log = LogFactory.getLog(DispatcherFilter.class);
    private AtomicBoolean initialized = new AtomicBoolean();
    private String encoding;
    private ServletContext servletContext;
    private Dispatcher dispatcher;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        if (initialized.compareAndSet(false, true)) {
        	this.encoding = filterConfig.getInitParameter("encoding");
            servletContext = filterConfig.getServletContext();
            this.dispatcher = DispatcherLoader.init(servletContext);
        }
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res,
                         FilterChain chain) throws IOException, ServletException {
        if (req.getCharacterEncoding() == null && encoding != null)
            req.setCharacterEncoding(encoding);
        final HttpServletRequest httpRequest= (HttpServletRequest) req;
        final HttpServletResponse httpResponse = (HttpServletResponse) res;

        RestRequest request = new RestRequest(httpRequest, dispatcher.getWebAppContext());
        RestHttp.create(request, httpResponse, servletContext);

        try {
            if (RestUrl.requestIsStaticFile(httpRequest)) {
                chain.doFilter(httpRequest, httpResponse);
            } else {
                dispatcher.dispatch();
            }
        } catch (ServletException e) {
            throw e;
        } finally {
            request.destory();
        }
    }

    @Override
    public void destroy() {
        log.info("Destroy Eternal...");
        dispatcher.destroy();
        dispatcher = null;
        servletContext = null;
    }
}

你可能感兴趣的:(filter,前置分发器,mvc控制器)