Introduction to Spring MVC Usage (iii)--interceptors

Source: Internet
Author: User

I. Overview

1. Interface definition

Interceptors are defined by the Handlerinterceptor interface:

 Public InterfaceHandlerinterceptor {//preprocessing Methods    BooleanPrehandle (HttpServletRequest request, httpservletresponse response, Object handler)throwsException; //post-processing methods    voidPosthandle (HttpServletRequest request, httpservletresponse response, Object handler, Modelandview Modelandview)throwsException; //post-Request-end processing method    voidAftercompletion (HttpServletRequest request, httpservletresponse response, Object handler, Exception ex)throwsException;}

Detailed Description:

    • Prehandle : preprocessing method, implement processor preprocessing (such as login check), third parameter is response processor; return value:
      • True: Indicates a continuation process (such as calling the next interceptor or processor)
      • False: Indicates a process interruption (such as a login check failure) and does not continue to invoke other interceptors or processors, at which point we need to generate a response via response
    • Posthandle : A post-processing method that implements post-processing of the processor (but before rendering the view), at which point we can process the model data through Modelandview (model and view objects), or to manipulate the views, Modelandview may also be null
    • aftercompletion : The entire request processing method, that is called when the view is rendered, can be performance monitoring or resource cleanup, similar to the finally in Try-catch-finally, But only the aftercompletion of the Interceptor that Prehandle returns true in the processor execution chain is called

2. Operation Process

Normal process:

Interrupt process:

Detailed reference to Dispatcherservlet.dodispatch () method source code

Second, a simple example

Interception device

Spring provides an handlerinterceptoradapter adapter that provides an empty implementation of the Handlerinterceptor interface, allowing us to implement only the required methods, so that the interceptor can inherit from the interface

 Public classTestinterceptorextendsHandlerinterceptoradapter {@Override Public BooleanPrehandle (HttpServletRequest request, httpservletresponse response, Object handler)throwsException {System.out.println ("This is Prehandle"); return true; } @Override Public voidPosthandle (HttpServletRequest request, httpservletresponse response, Object handler, Modelandview Modelandview)throwsException {System.out.println ("This is Posthandle"); } @Override Public voidAftercompletion (HttpServletRequest request, httpservletresponse response, Object handler, Exception ex)throwsException {System.out.println ("This is Aftercompletion"); }}

Controller

 Public class Implements Controller {    publicthrows  Exception {        System.out.println ("This is TestController2 ");         return New Modelandview ("Hello2");}    }

Xml

<?XML version= "1.0" encoding= "UTF-8"?><Web-appversion= "3.0"xmlns= "Http://java.sun.com/xml/ns/javaee"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" /c11>>  <Display-name>Archetype Created Web Application</Display-name>    <servlet>          <Servlet-name>Test-servlet</Servlet-name>          <Servlet-class>Org.springframework.web.servlet.DispatcherServlet</Servlet-class>          <Init-param>            <Param-name>Contextconfiglocation</Param-name>            <Param-value>Classpath:spring-mvc.xml</Param-value>        </Init-param>        <Load-on-startup>1</Load-on-startup>      </servlet>      <servlet-mapping>          <Servlet-name>Test-servlet</Servlet-name>          <Url-pattern>/</Url-pattern>      </servlet-mapping> </Web-app>

Spring-mvc.xml: Registering Interceptors and controllers

<?XML version= "1.0" encoding= "UTF-8"?><Beansxmlns= "Http://www.springframework.org/schema/beans"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2. XSD ">              <!--handlermapping -      <Beanclass= "Org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping">        < Propertyname= "Interceptors">              <List>                 <refBean= "Testinterceptor"/>              </List>          </ Property>      </Bean>             <!--Handleradapter -      <Beanclass= "Org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>         <!--Viewresolver -      <Beanclass= "Org.springframework.web.servlet.view.InternalResourceViewResolver">          < Propertyname= "Viewclass"value= "Org.springframework.web.servlet.view.JstlView"/>          < Propertyname= "prefix"value= "/web-inf/jsp/"/>          < Propertyname= "suffix"value= ". jsp"/>      </Bean>          <Beanname= "/hello2"class= "Cn.matt.controller.TestController2"/>        <Beanname= "Testinterceptor"class= "Cn.matt.interceptor.TestInterceptor"/>    </Beans>

hello2.jsp

<%@ Page Language="Java" %><HTML><Head><Metahttp-equiv= "Content-type"content= "text/html; charset=iso-8859-1"><title>Insert Title here</title></Head><Body>Hello2</Body></HTML>

Access Http://localhost:8080/myweb/hello2, console output:

This is Prehandlethis is Testcontroller2this are Posthandlethis is aftercompletion

It is recommended that the functionality implemented using filter filters in the SERVLET specification be implemented with the filter, because Handlerinteceptor is only available in the Spring WEB MVC environment, so filter is the most common and should be used first. For more information, refer to Javaweb Learning Summary (42)--filter (filter) Learning

Reference:

Fifth Chapter Processor Interceptor--Follow the Tao Springmvc

Javaweb Learning Summary (42)--filter (filter) Learning

Introduction to Spring MVC Usage (iii)--interceptors

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.