Interceptors in springMVC are used to intercept the execution of controller methods.

Create some pre-conditions:

<a th:href="@{/testInterceptor}">Copy the code

The backend:

@Controller public class TestController { @RequestMapping("/testInterceptor") public String testInterceptor() { return "success"; }}Copy the code

Create interceptors

Create a new package, interceptors, FirstInterceptor, and implement the HandlerInterceptor interface.

Shortcut key Ctrl + O, quick rewrite method, 3 in the diagram.

public class FirstInterceptor implements HandlerInterceptor { public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("FirstInterceptor --> preHandle"); return false; } public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("FirstInterceptor --> postHandle"); } public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("FirstInterceptor --> afterCompletion"); }}Copy the code
  • PreHandle: executes before the current controller method executes.
  • PostHandle: Executes after the current controller method executes.
  • AfterCompletion: Execute after rendering the view after processing the view and model data.

Configure interceptors

Configure the interceptor in the springMVC configuration file. The object is the FirstInterceptor class:

<! - configure interceptor - > < MVC: interceptors > < bean class = "com. Pingguo. MVC. Interceptors. FirstInterceptor" > < / bean > < / MVC: interceptors >Copy the code

Redeploy, visit http://localhost:8080/springmvc/, found that the blank page, view controller log see print:

The interception succeeds.

Of the three methods rewritten above, only preHandle returns a value, which is Boolean: false for intercept and true for pass.

Change the return value of preHandle to true. After redeployment, the home page can be accessed successfully.

Looking at the console printout, you can see that before rendering, the first two methods are executed: preHandle and postHandle.

After a lot of Thymeleaf rendering, the last afterCompletion is executed.

Now continue to click on the home page of the new hyperlink, found will also be blocked release.

Note In this configuration mode, all requests are blocked.

Set requests that do not need to be intercepted

Interceptors can be set via ref or bean tags:

  • throughmvc:mappingSets the request to intercept
  • throughmvc:exclude-mappingSet requests to exclude
<bean name="firstInterceptor" class="com.pingguo.mvc.interceptors.FirstInterceptor"></bean> <! < MVC :interceptors> < MVC :interceptor> < MVC :mapping path="/**"/> < MVC :exclude-mapping path="/"></mvc:exclude-mapping> <ref bean="firstInterceptor"></ref> </mvc:interceptor> </mvc:interceptors>Copy the code

Note that I registered a bean externally called firstInterceptor for ref reference.

  • <mvc:mapping path="/**"/>Intercepts all requests.
  • <mvc:exclude-mapping path="/">Is not blocked except for the home page.

That is to say, when I visit http://localhost:8080/springmvc/, now should not be intercepted. http://localhost:8080/springmvc/testInterceptor will be stopped.

Try to visit http://localhost:8080/springmvc/:

The home page opens normally, and the console does not output the interceptor contents:

Now continue to visit http://localhost:8080/springmvc/testInterceptor,

Intercepted.

Sequence of execution of multiple interceptors

Go ahead and create a new SecondInterceptor, noting that THIS time I added @Component to make it easier to use the ref reference directly in the configuration file.

@Component public class SecondInterceptor implements HandlerInterceptor { public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("SecondInterceptor --> preHandle"); return true; } public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("SecondInterceptor --> postHandle"); } public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("SecondInterceptor --> afterCompletion"); }}Copy the code

Modify interceptor configuration:

<! <ref bean="secondInterceptor"></ref> <ref bean="secondInterceptor"></ref> </mvc:interceptors>Copy the code

Redeploy, visit the http://localhost:8080/springmvc/ home page, check the console printout.

As you can see, the preHandle methods are executed in the order FirstInterceptor->SecondInterceptor. The other two methods are reversed.

If the preHandle() of each interceptor returns true:

  • The order of execution depends on the order in the configuration, in the upper interceptorfirstInterceptorIs in thesecondInterceptorThe front.
  • preHandle()Will be executed in the order configured, andPostHandle () andAfterComplation () ‘is executed in reverse order.

If an interceptor’s preHandle() returns false:

  • preHandle()returnfalseAnd itbeforeInterceptor ofpreHandle()Will be executed.
  • postHandle()None of them.
  • returnfalseThe interceptorbeforeInterceptor ofafterComplation()Will perform.

Change the preHandle() on SecondInterceptor to return false.

As expected.

These processes can be interrupted to see the source code execution process.