国产xxxx99真实实拍_久久不雅视频_高清韩国a级特黄毛片_嗯老师别我我受不了了小说

資訊專欄INFORMATION COLUMN

[鬧著玩-2]spring-mvc 主要流程

fuchenxuan / 2168人閱讀

摘要:源碼倉庫本文倉庫三層結構表現層模型業務層持久層工作流程用戶前端控制器用戶發送請求前端控制器后端控制器根據用戶請求查詢具體控制器后端控制器前端控制器處理后結果前端控制器視圖視圖渲染視圖前端控制器返回視圖前端控制器用戶響應結

SpringMvc

【源碼倉庫】
【本文倉庫】

三層結構

表現層

MVC模型

業務層

service

持久層

dao

工作流程
用戶->前端控制器:用戶發送請求
前端控制器-> 后端控制器:根據用戶請求查詢具體控制器
后端控制器-->前端控制器:處理后結果
前端控制器--> 視圖:視圖渲染
視圖-->前端控制器:返回視圖
前端控制器--> 用戶:響應結果

簡單案例

依賴



    4.0.0

    com.huifer
    mySpringMvcBook
    1.0-SNAPSHOT

    war

    
        UTF-8
        UTF-8
        1.8
        5.1.5.RELEASE
        4.12
    


    
        org.springframework
        spring-beans
        ${spring.version}
    
    
        org.springframework
        spring-core
        ${spring.version}
    
    
        org.springframework
        spring-context
        ${spring.version}
    
    
        org.springframework
        spring-expression
        ${spring.version}
    

    
        org.springframework
        spring-aspects
        ${spring.version}
    
    
        aopalliance
        aopalliance
        1.0
    

    
        org.springframework
        spring-webmvc
        ${spring.version}
    
    
        org.springframework
        spring-web
        ${spring.version}
    


    
    
        javax.servlet.jsp.jstl
        jstl
        1.2
    
    
        javax.servlet
        servlet-api
        2.5
    
    
        org.projectlombok
        lombok
        1.18.4
    
    
        com.fasterxml.jackson.core
        jackson-databind
        2.9.3
    
    
    
        com.fasterxml.jackson.core
        jackson-core
        2.9.3
    
    
    
        com.fasterxml.jackson.core
        jackson-annotations
        2.9.3
    


    
        
            
            
                src/main/java
                
                    **/*.xml
                
            
        
        
            
                org.apache.maven.plugins
                maven-compiler-plugin
                
                    1.8
                    1.8
                    UTF-8
                
            
        
    

spring-config




    


    
    


web.xml





    
        springmvc
        org.springframework.web.servlet.DispatcherServlet
        
            contextConfigLocation
            classpath:spring-mvc-config.xml
        
        
        2

    
    
        springmvc
        /
    

controller

@Controller
@RequestMapping("item")
public class ItemController {
    @ResponseBody
    @GetMapping("/query")
    public ModelAndView query() throws Exception {

        List itemList = new ArrayList<>();
        itemList.add(new Item("吃的", 3.3, new Date()));
        itemList.add(new Item("玩的", 3.3, new Date()));
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("itemList", itemList);
        modelAndView.setViewName("/WEB-INF/jsp/item.jsp");
        return modelAndView;
    }

}

item.JSP

<%--
  Created by IntelliJ IDEA.
  User: huifer
  Date: 2019/3/10
  Time: 11:26
  To change this template use File | Settings | File Templates.
--%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" isELIgnored="false" %>



    ItemList


ITEM

${itemList}

根據tomcat的web.xml配置可以看到 /jsp的攔截是分開的 ,而我們直接用一個/*來攔截那么tomcat將不知道用什么來處理

spring-mvc大致流程源碼翻閱

從配置文件中知道前端控制器DispatcherServlet


    springmvc
    org.springframework.web.servlet.DispatcherServlet
    
        contextConfigLocation
        classpath:spring-mvc-config.xml
    
    
    2

在org.springframework.web.servlet.DispatcherServlet 看下面兩個方法

doService 將訪問的數據接收到交給doDispatch

doDispatch 具體調度

protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpServletRequest processedRequest = request;
        HandlerExecutionChain mappedHandler = null;
        boolean multipartRequestParsed = false;
        WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);

        try {
            try {
                ModelAndView mv = null;
                Object dispatchException = null;

                try {
                    processedRequest = this.checkMultipart(request);
                    multipartRequestParsed = processedRequest != request;
                       // 加載handler
                    mappedHandler = this.getHandler(processedRequest);
                    if (mappedHandler == null) {
                        this.noHandlerFound(processedRequest, response);
                        return;
                    }
                    // handler適配器
                    HandlerAdapter ha = this.getHandlerAdapter(mappedHandler.getHandler());
                    String method = request.getMethod();
                    boolean isGet = "GET".equals(method);
                    if (isGet || "HEAD".equals(method)) {
                        long lastModified = ha.getLastModified(request, mappedHandler.getHandler());
                        if ((new ServletWebRequest(request, response)).checkNotModified(lastModified) && isGet) {
                            return;
                        }
                    }

                    if (!mappedHandler.applyPreHandle(processedRequest, response)) {
                        return;
                    }
                    // 適配器執行操作
                    mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
                    if (asyncManager.isConcurrentHandlingStarted()) {
                        return;
                    }

                    this.applyDefaultViewName(processedRequest, mv);
                    mappedHandler.applyPostHandle(processedRequest, response, mv);
                } catch (Exception var20) {
                    dispatchException = var20;
                } catch (Throwable var21) {
                    dispatchException = new NestedServletException("Handler dispatch failed", var21);
                }
                // 操作結果返回
                this.processDispatchResult(processedRequest, response, mappedHandler, mv, (Exception)dispatchException);
            } catch (Exception var22) {
                this.triggerAfterCompletion(processedRequest, response, mappedHandler, var22);
            } catch (Throwable var23) {
                this.triggerAfterCompletion(processedRequest, response, mappedHandler, new NestedServletException("Handler processing failed", var23));
            }

        } finally {
            if (asyncManager.isConcurrentHandlingStarted()) {
                if (mappedHandler != null) {
                    mappedHandler.applyAfterConcurrentHandlingStarted(processedRequest, response);
                }
            } else if (multipartRequestParsed) {
                this.cleanupMultipart(processedRequest);
            }

        }
    }

handler怎么來

initHandlerMappings(context)

protected void initStrategies(ApplicationContext context) {
        this.initMultipartResolver(context);
        this.initLocaleResolver(context);
        this.initThemeResolver(context);
        this.initHandlerMappings(context);
        this.initHandlerAdapters(context);
        this.initHandlerExceptionResolvers(context);
        this.initRequestToViewNameTranslator(context);
        this.initViewResolvers(context);
        this.initFlashMapManager(context);
    }

    private void initHandlerMappings(ApplicationContext context) {
        this.handlerMappings = null;
        if (this.detectAllHandlerMappings) {
            Map matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(context, HandlerMapping.class, true, false);
            if (!matchingBeans.isEmpty()) {
                this.handlerMappings = new ArrayList(matchingBeans.values());
                AnnotationAwareOrderComparator.sort(this.handlerMappings);
            }
        } else {
            try {
                HandlerMapping hm = (HandlerMapping)context.getBean("handlerMapping", HandlerMapping.class);
                this.handlerMappings = Collections.singletonList(hm);
            } catch (NoSuchBeanDefinitionException var3) {
            }
        }

        if (this.handlerMappings == null) {
            // 讀取默認配置文件
            this.handlerMappings = this.getDefaultStrategies(context, HandlerMapping.class);
            if (this.logger.isTraceEnabled()) {
                this.logger.trace("No HandlerMappings declared for servlet "" + this.getServletName() + "": using default strategies from DispatcherServlet.properties");
            }
        }

    }

默認配置文件

handler適配器也在配置文件中

    protected HandlerAdapter getHandlerAdapter(Object handler) throws ServletException {
        if (this.handlerAdapters != null) {
            Iterator var2 = this.handlerAdapters.iterator();

            while(var2.hasNext()) {
                HandlerAdapter adapter = (HandlerAdapter)var2.next();
                  // 是否能夠適配
                if (adapter.supports(handler)) {
                    return adapter;
                }
            }
        }

        throw new ServletException("No adapter for handler [" + handler + "]: The DispatcherServlet configuration needs to include a HandlerAdapter that supports this handler");
    }

HttpRequestHandlerAdapter

public class HttpRequestHandlerAdapter implements HandlerAdapter {
    public HttpRequestHandlerAdapter() {
    }
// 判斷是否是當前類支持的適配器
    public boolean supports(Object handler) {
        return handler instanceof HttpRequestHandler;
    }

// 適配器執行操作
    @Nullable
    public ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        ((HttpRequestHandler)handler).handleRequest(request, response);
        return null;
    }

    public long getLastModified(HttpServletRequest request, Object handler) {
        return handler instanceof LastModified ? ((LastModified)handler).getLastModified(request) : -1L;
    }
}

視圖解析

 private void processDispatchResult(HttpServletRequest request, HttpServletResponse response, @Nullable HandlerExecutionChain mappedHandler, @Nullable ModelAndView mv, @Nullable Exception exception) throws Exception {
        boolean errorView = false;
        if (exception != null) {
            if (exception instanceof ModelAndViewDefiningException) {
                this.logger.debug("ModelAndViewDefiningException encountered", exception);
                mv = ((ModelAndViewDefiningException)exception).getModelAndView();
            } else {
                Object handler = mappedHandler != null ? mappedHandler.getHandler() : null;
                mv = this.processHandlerException(request, response, handler, exception);
                errorView = mv != null;
            }
        }

        if (mv != null && !mv.wasCleared()) {
              // 這個地方在做渲染
            this.render(mv, request, response);
            if (errorView) {
                WebUtils.clearErrorRequestAttributes(request);
            }
        } else if (this.logger.isTraceEnabled()) {
            this.logger.trace("No view rendering, null ModelAndView returned.");
        }

        if (!WebAsyncUtils.getAsyncManager(request).isConcurrentHandlingStarted()) {
            if (mappedHandler != null) {
                mappedHandler.triggerAfterCompletion(request, response, (Exception)null);
            }

        }
    }
protected void render(ModelAndView mv, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Locale locale = this.localeResolver != null ? this.localeResolver.resolveLocale(request) : request.getLocale();
        response.setLocale(locale);
        String viewName = mv.getViewName();
        View view;
        if (viewName != null) {
            // 視圖解析器
            view = this.resolveViewName(viewName, mv.getModelInternal(), locale, request);
            if (view == null) {
                throw new ServletException("Could not resolve view with name "" + mv.getViewName() + "" in servlet with name "" + this.getServletName() + """);
            }
        } else {
            view = mv.getView();
            if (view == null) {
                throw new ServletException("ModelAndView [" + mv + "] neither contains a view name nor a View object in servlet with name "" + this.getServletName() + """);
            }
        }

        if (this.logger.isTraceEnabled()) {
            this.logger.trace("Rendering view [" + view + "] ");
        }

        try {
            if (mv.getStatus() != null) {
                response.setStatus(mv.getStatus().value());
            }
            // 視圖的渲染函數渲染到頁面上
            view.render(mv.getModelInternal(), request, response);
        } catch (Exception var8) {
            if (this.logger.isDebugEnabled()) {
                this.logger.debug("Error rendering view [" + view + "]", var8);
            }

            throw var8;
        }
    }
@Nullable
protected View resolveViewName(String viewName, @Nullable Map model, Locale locale, HttpServletRequest request) throws Exception {
    if (this.viewResolvers != null) {
        Iterator var5 = this.viewResolvers.iterator();

        while(var5.hasNext()) {
            // 視圖解析器
            ViewResolver viewResolver = (ViewResolver)var5.next();
            View view = viewResolver.resolveViewName(viewName, locale);
            if (view != null) {
                return view;
            }
        }
    }

    return null;
}

spring-mvc請求具體流程圖
用戶->前端控制器
 org.springframework.web.servlet.DispatcherServlet
 用來接收響應以及返回響應結果:1.用戶發送請求 
前端控制器
 org.springframework.web.servlet.DispatcherServlet
 用來接收響應以及返回響應結果 -> HandlerMapper : 2.根據url進行處理
HandlerMapper -> 前端控制器
 org.springframework.web.servlet.DispatcherServlet
 用來接收響應以及返回響應結果:3.將handlerMapper處理結果給前端控制器
前端控制器
 org.springframework.web.servlet.DispatcherServlet
 用來接收響應以及返回響應結果-> HandlerAdapter:4.給適配器確認具體的適配器,比如我們這里給了HttpRequestHandlerAdapter
HandlerAdapter ->ModelAndView:5.用來執行業務操作
ModelAndView ->HandlerAdapter: 6.執行完成給HandlerAdapter返回
HandlerAdapter->前端控制器
 org.springframework.web.servlet.DispatcherServlet
 用來接收響應以及返回響應結果:7.返回一個modelAndView
前端控制器
 org.springframework.web.servlet.DispatcherServlet
 用來接收響應以及返回響應結果-> ViewResolver 視圖解析器 :8.將第7步中的view進行解析
ViewResolver 視圖解析器->前端控制器
 org.springframework.web.servlet.DispatcherServlet
 用來接收響應以及返回響應結果:9.解析結果返回
前端控制器
 org.springframework.web.servlet.DispatcherServlet
 用來接收響應以及返回響應結果 -> View : 9.將model渲染到view中
View->前端控制器
 org.springframework.web.servlet.DispatcherServlet
 用來接收響應以及返回響應結果: 10.view 結果返回給前端控制器
前端控制器
 org.springframework.web.servlet.DispatcherServlet
 用來接收響應以及返回響應結果 --> 用戶:查看到完整的網頁

文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。

轉載請注明本文地址:http://specialneedsforspecialkids.com/yun/73641.html

相關文章

  • spring-MVC源碼解讀(一)

    摘要:處理器是繼前端控制器的后端控制器,在的控制下對具體的用戶請求進行處理。由于涉及到具體的用戶業務請求,所以一般情況需要程序員根據業務需求開發。 1、mcv整體架構和流程 showImg(https://segmentfault.com/img/bV55Qq?w=860&h=406); 用戶發送請求至前端控制器 DispatcherServlet DispatcherServlet 收到...

    I_Am 評論0 收藏0
  • SSM框架運行機制

    摘要:框架搭建首先下載相應的包,對于包有兩種方式使用創建依賴從而導入所需的包。總結主要進行頁面的請求接受與響應。組件包括前端控制器,處理器映射器,處理器適配器,視圖解析器,處理器,視圖。 我之前的文章介紹了如何搭建SSH框架以及如何利用這一框架來進行web應用開發,最近我又接觸了SSM框架即Spring+SpringMVC+Mybatis三大框架的整合,而且目前該框架就SSH框架而言使用的較...

    winterdawn 評論0 收藏0
  • SpringMVC入門筆記

    摘要:入門筆記簡介是一種基于的實現了設計模式的請求驅動類型的輕量級框架,是系開源項目中的一個,和配合使用。配置在中需要添加使用的和映射規則。入門較快,而掌握起來相對較難。 SpringMVC入門筆記 1. 簡介 Spring MVC是一種基于Java的實現了Web MVC設計模式的請求驅動類型的輕量級Web框架 ,是Spring系開源項目中的一個,和IoC配合使用。通過策略接口,Spring...

    zhaochunqi 評論0 收藏0
  • spring-mvc注解

    摘要:關鍵注解的關鍵注解主要有其中主要是用于標記該類是一個控制器,用于指示的哪一個類或方法來處理請求動作,即用于標識具體的處理器。默認已經裝配了作為組件的實現類,而由使用,將請求信息轉換為對象。 關鍵注解 springmvc的關鍵注解主要有@Controller/@RequestMapping/@RequestParam/@PathVariable/@RequestHeader/@Cooki...

    EdwardUp 評論0 收藏0

發表評論

0條評論

fuchenxuan

|高級講師

TA的文章

閱讀更多
最新活動
閱讀需要支付1元查看
<