设为首页 加入收藏

TOP

Spring入门进阶之DispatcherServlet源码分析(六)
2018-01-17 13:05:27 】 浏览:957
Tags:Spring 入门 进阶 DispatcherServlet 源码 分析
行封装处理,跟进SimpleUrlHandlerMapping的getHandler方法:


public final HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
    // 根据request获取对应的handler
    Object handler = getHandlerInternal(request);
    if (handler == null) {
        // 如果没有则使用默认的handler
        handler = getDefaultHandler();
    }
    if (handler == null) {
        return null;
    }


    if (handler instanceof String) {
        String handlerName = (String) handler;
        handler = getApplicationContext().getBean(handlerName);
    }
    return getHandlerExecutionChain(handler, request);
}


上面源码应该很清晰,根据request获取对应的Handler,如果没有的话则使用默认的,当查找到的controller为String类型时,就意味着返回的是配置的bean名称,需要根据bean名称查找对应的bean,最后通过getHandlerExecutionChain方法对返回的Handler进行封装,以满足返回类型的匹配。
接着跟进getHandlerInternal方法源码来看看怎样根据request查找对应的Handler:


protected Object getHandlerInternal(HttpServletRequest request) throws Exception {
    // 获取用于匹配的url有效路径
    String lookupPath = getUrlPathHelper().getLookupPathForRequest(request);
    // 根据上面的路径寻找handler
    Object handler = lookupHandler(lookupPath, request);
    if (handler == null) {
        // We need to care for the default handler directly, since we need to
        // expose the PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE for it as well.
        Object rawHandler = null;
        if ("/".equals(lookupPath)) {
            // 如果请求的路径是“/”,则使用RootHandler进行处理
            rawHandler = getRootHandler();
        }
        if (rawHandler == null) {
            rawHandler = getDefaultHandler();
        }
        if (rawHandler != null) {
            // 根据beanName获取对应的bean
            if (rawHandler instanceof String) {
                String handlerName = (String) rawHandler;
                rawHandler = getApplicationContext().getBean(handlerName);
            }
            validateHandler(rawHandler, request);
            handler = buildPathExposingHandler(rawHandler, lookupPath, lookupPath, null);
        }
    }
    if (handler != null && logger.isDebugEnabled()) {
        logger.debug("Mapping [" + lookupPath + "] to " + handler);
    }
    else if (handler == null && logger.isTraceEnabled()) {
        logger.trace("No handler mapping found for [" + lookupPath + "]");
    }
    return handler;
}


protected Object lookupHandler(String urlPath, HttpServletRequest request) throws Exception {
    // 直接匹配情况的处理
    Object handler = this.handlerMap.get(urlPath);
    if (handler != null) {
        // Bean name or resolve

首页 上一页 3 4 5 6 7 8 9 下一页 尾页 6/10/10
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Java中BigDecimal的基本运算 下一篇Java静态代码块使用

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目