HandlerExecutionChain、HandlerMapping、HandlerAdapter之间的关系,以及springmvc的请求流程

对于HandlerExecutionChain

public class HandlerExecutionChain {
    //实际的请求处理器,用来控制我们的请求到达哪个对象的哪个方法
    private final Object handler;
    
    public Object getHandler() {
        return this.handler;
    }
	//处理实际请求前的一些操作
    boolean applyPreHandle(HttpServletRequest request, HttpServletResponse response) throws Exception {
			.....
			.....
    }
	//请求处理完成后的一些操作
    void applyPostHandle(HttpServletRequest request, HttpServletResponse response, @Nullable ModelAndView mv)
            throws Exception {
			.....
			.....
    }
}

可以看出:HandlerExecutionChain是实际的处理器的一个包装对象,它包含实际的处理器和一些请求前后的处理流程。

对于HandlerMapping

public interface HandlerMapping {
	HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception;
}

该接口只有一个方法getHandler,它的入参是HttpServletRequest,输出是HandlerExecutionChain。很明显,它通过当前请求的request对象,来获取到一个包含实际请求处理器的HandlerExecutionChain对象

对于HandlerAdapter

public interface HandlerAdapter {
	boolean supports(Object handler);
	@Nullable
	ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception;
}

该接口只有一个方法handle,调用处理器handler,返回一个ModelAndView对象。
由上面的分析我们大概可以写一个springmvc基本的请求处理流程

void doDispatch(HttpServletRequest request, HttpServletResponse response){

	//容器初始化时会默认加载几种HandlerMapping,也可自己配置。这里为了简单说明流程,不再说明具体细节。假已经有了一个`HandlerMapping`对象
	HandlerMapping handlerMapping;
	
	//handlerMapping根据请求获取处理器,幷包装成HandlerExecutionChain
	//getHandler方法的细节省略
	HandlerExecutionChain handlerExecutionChain =  handlerMapping.getHandler(request)//请求前的处理
	handlerExecutionChain.applyPreHandle(request,response);
	
	//从handlerExecutionChain获取实际处理器
	Object handler = handlerExecutionChain.getHandler();
	//根据实际处理器获取处理器的适配器,getHandlerAdapter方法细节省略
	HandlerAdapter handlerAdapter = getHandlerAdapter(handler);
	
	//调用适配器处理请求,返回一个`ModelAndView`对象
	ModelAndView mv = handlerAdapter.handle(HttpServletRequest request, HttpServletResponse response, Object handler)
	
	//请求经适配器处理后的一些操作
	handlerExecutionChain.applyPostHandle(HttpServletRequest request, HttpServletResponse response, @Nullable ModelAndView mv)
}

原文链接

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章