Java framework SpringMVC 05- interceptors - -Spring exception mapping workflow

SpringMVC

Interceptor

  Spring MVC may also be used interceptors request intercept processing, can custom interceptor to perform specific functions, custom interceptor may implement HandlerInterceptor interfaces in three th methods , may be inherited HandlerInterceptorAdapter  adapter class that method as needed, which method is achieved

Filter and interceptor difference

  Filters: The filter operation prior Servlet
  blockers: interceptor after Servlet, the request processor (Controller) before operation.

Interceptor three methods

  ①  The preHandle (): This method (Controller) is called before the processor is processing the request , the process request for processing the user request. Also if the call request interceptor to intercept other interceptors process, or to a service processor for processing returns  to true ; if you do not call other components to process the request, false is returned. (Returns false if the subsequent operations are not performed, it is similar to the filter doFilter not normally return false)

  ②  The postHandle (): This method (Controller) post-processed the request, but  DispatcherServlet returned to the client before responding (view before rendering) is called , the process request for processing the user request.

  ③  afterCompletion (): This method DispatcherServlet after completely processed request (forwarding | after redirection) is called , can be shut down to clean up some resources operations in the process.

Configuring interceptors

< MVC: interceptors > 
        <-!    All requests interceptors may also be provided already assembled ref reference interceptor -> 
        < the bean ID = "firstHandlerInterceptor" class = "main.controller.FirstHandlerInterceptor" > </ the bean > 
        < MVC: interceptor > 
            <-!      indicates only the specified interceptor intercepts all requests / test / in -> 
            < MVC: Mapping path = "/ test / ** /" /> 
            ! <-      represents an access / test / Test .do not trigger a request interceptor -> 
            < MVC:-Mapping the exclude path = "/ Test / test.do" /> 
         <!-      Set interceptor request may also be specified by reference ref has been assembled interceptor -> 
         <bean id="testInterceptor" class="main.controller.TestInterceptor"></bean> 
        </mvc:interceptor> 
</mvc:interceptors>

 Program execution order

  1. preHandle) (: Before execution request (Controller) requesting processor performs a method. 
  2. Request execution processor (Controller) method
  after the execution request of the requesting processor (Controller) method, prior to rendering the view: 3. postHandle ().
  4. view rendering
  performed after | view rendering (are redirected): 5. afterCompletion ().

Multiple interceptors execution process

  When the execution order in the presence of a plurality of interceptors, determined by the configuration sequence. (PreHandle () configure, execute) 
  preHandle (): configuration and interceptors order consistent .
  postHandle (): Configure the interceptor order opposite . Bottom reverse cycle call
  afterCompletion (): interceptors arranged opposite order.

preHandle () return value of false works

  The preHandle first interceptor () returns a value of false:
    the implementation of only the first interceptor preHandle () method is executed finished, return; (not performing subsequent method) 
  is not the first interceptors The preHandle ( ) returns false: 
    before the current interceptor interceptor afterCompletion () will be executed.

  When two interceptor The preHandle () method returns true, the imaginary line accordance

  When the second interceptor The preHandle () returns false accordance implemented route

 Exception Handling

  In SpringMVC, the request regardless of whether there is abnormality in the controller, the object will return ModelAndView

  Exception handler HandlerExceptionResolver the abnormality occurs Handler include mapping data and the target binding method performed when Spring MVC

  DispatcherServlet default assembly  HandlerExceptionResolver DefaultHandlerExceptionResolver parser will automatically have a standard Spring MVC ANALYTICAL as HTTP error status code

  Use  <mvc: annotation-driven /> After the new configuration will be assembling Spring3.0 exception resolvers to achieve a finer process. If you want to deal with all exceptions or specify a unified abnormal jump page, you can use SimpleMappingExceptionResolver, it will be an exception class name maps to view name, can be realized jump to a specific page , and report exceptions.

Configuring exception resolvers

    < Bean class = "org.springframework.web.servlet.handler.SimpleMappingExceptionResolver" > 
        <-!     All abnormal define the default processing page, exceptionMappings undefined, 
                value represents a jump page, as the file path and suffix already viewResolver specified -> 
        < Property name = "defaultErrorView" value = "error" > </ Property > 
        <-!     custom exception handling variable names used to obtain the page exception information, is stored in the request field -> 
        < Property name = "exceptionAttribute" value = "Exception" > </ Property > 
        <!-     require special handling abnormal, full class name as key, page file name as abnormal values can be mapped to different exception different page ->
        <property name="exceptionMappings">
            <props>
                <prop key="java.lang.NullPointerException">nullPointer</prop>
            </props>
        </property>
    </bean>

<mvc:annotation-driven/>

  Is spring MVC distribution request for the @Controllers necessary, that enable annotation-driven to address the premise @Controller annotation configuration used.

  It also provides: data binding support, @ NumberFormatannotation support, @ DateTimeFormat support, @ Valid support for reading and writing XML support (JAXB, read and write JSON support (Jackson).

  It will be automatically registered for us a lot of Bean, the most important thing is RequestMappingHandlerMapping and RequestMappingHandlerAdapter .

    The first one is the implementation class HandlerMapping, it processes @RequestMapping annotations, and it requests to register mapping table.
    The second is HandlerAdapter implementation class, which is a processing request to the adapter, that white, which is a method to determine which type of call, and the constructor arguments, return values.

  Simply put, what comment, we need to declare a corresponding BeanPostProcessor. While Spring provides us with an extremely convenient way to register these BeanPostProcessor, that use a variety of tags to implicitly registered to Spring container

Spring Workflow

  Related classes

    The HandlerMapping (mapping object requesting processor): defines the mapping relationship between the object and a request processor requests all objects

    HandlerExecutionChain (Object Request handler execution chain): defines the current request handler object, and all objects interceptors.

    HandlerAdapter is (adapter object requesting processor): a method invocation request to the current request processor.

  Execution flow FIG understood corresponding lower

    1) the user sends a request to the server, the request is captured SpringMVC front controller DispatcherServlet

    2) DispatcherServlet parsing the request URL to obtain the requested resource identifier (URI): if the request URI corresponding mapping
      ① absent:
        and then determines whether the configuration mvc: default-servlet-handler:
        if not configured, the message mapping console Find less than, the client display 404 error
        if there is configured, the execution of the target resource (usually static resources, such as: JS, CSS, HTML)
      ② exist:
        perform the following procedure

    3) According to the URI, call HandlerMapping obtain all the objects arranged Handler (including Handler Handler object corresponding to the object and the interceptor), and finally returned as HandlerExecutionChain object;

    4) DispatcherServlet obtained in accordance with Handler, select a suitable HandlerAdapter.

    5) If successful HandlerAdapter, this time will begin preHandler blocker (...) method [forward]

    6) Extraction of model data Request, filling into the reference Handler, Handler started (the Controller) method, processing the request. In the parameters during the filling Handler in, depending on your configuration, Spring will help you to do extra work:
      ① HttpMessageConveter: a request message (e.g. Json, xml, etc. data) into an object, convert the object to respond to specific information
      ② data conversion: conversion of the data request message. The String is converted into Integer, Double, etc.
      ③ Data Format: data format of the request message. As will be converted into a string format or a digital format date
      ④ Data Validation: validation of the data (the length, format, etc.), verification result storage or Error to BindingResult

    After 7) Handler executed, a return to the DispatcherServlet ModelAndView object;

    8) At this time, the interceptor postHandle begin (...) method [reverse]

    9) The ModelAndView return (in this case determines whether there is an abnormality: if there is an exception, exception handling is performed HandlerExceptionResolver) selecting a suitable ViewResolver (Spring must be registered to the container ViewResolver) is returned to the DispatcherServlet, and according to the Model view, to render the view

    10) AfterCompletion approach requires interceptor when returned to the client [reverse]

    11) render results back to the client

 

Spring与SpringMVC

  SpringMVC relationship spring container and container objects

    springMVC container object, pay a default management DispatcherServlet

    spring container object, we need to manage (to the Listener management)

  Object Description spring containers

    Root WebApplicationContext: root of context hierarchy

  springMVC container object described

    WebApplicationContext for namespace 'springDispatcherServlet-servlet':root of context hierarchy

  spring is the parent container object, springMVC container object is a child. Subclass can call the parent class method directly.

  The IOC SpringMVC bean container can reference Spring IOC container bean. Vice versa. 

  In a web application, obtaining the container object mode spring

ServletContext servletContext = httpSession.getServletContext();
ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext);

 

  在web应用下,获取springMVC容器对象可直接通过装配属性的方式获取

    @Autowired
    private XmlWebApplicationContext context;

配置文件

  若 Spring 的 IOC 容器和 SpringMVC 的 IOC 容器扫描组件的包有重合的部分, 就会导致有的 bean 会被创建 2 次,可通过一个包含一个排除的方式解决

Guess you like

Origin www.cnblogs.com/Open-ing/p/12230419.html