SPRINGMVC Interceptors:
1. First we need to introduce a jar package, which is needless to say,
Define your own interceptor implementation handlerinterceptor and rewrite the method.
2. Configure Web. xml
?
1234567891011121314151617 |
<!--中央调度器-->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-
class
>org.springframework.web.servlet.DispatcherServlet</servlet-
class
>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</init-param>
<!-- TOmcat启动的时候,Servlet对象就存储到内存 正整数 -->
<load-on-startup>
1
</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.
do
</url-pattern>
</servlet-mapping>
|
3. Configuring a Processor controller
4. Define the large configuration Applicationcontext.xml
?
123456789 |
<!-- 包扫描器 -->
<context:component-scan base-
package
=
"cn.hq.controller"
></context:component-scan>
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path=
"/**"
/>
<bean
class
=
"cn.hq.interceptor.MyInterceptor"
></bean>
</mvc:interceptor>
</mvc:interceptors>
|
Note: The return value of the first method in the interceptor's method now is false
Effect Demo:
After the request we will find the console output a field
It is because we set its return value type, so request go home, sadly end, he needs us to solve him.
When you've unpacked him (true), ask again:
Attach one more Picture:
Method parsing:
The first method, Prehandle , is especially important, and it can be based on the return value
Change the process of request down, play a leading role, the second method Poshandle, he can in
After the request passes through the processor, a series of operations are followed, and finally the last method
aftercompletion, which responds to the client.
Configuration of multiple interceptors:
?
12345678 |
<!-- 定义多个拦截器 --> <mvc:interceptors> <mvc:interceptor> <mvc:mapping path= "/**" /> <bean class = "cn.hq.interceptor.MyInterceptor2" ></bean> </mvc:interceptor> </mvc:interceptors> |
Test steps, configure an interceptor more
Test Case 1, turn on the first interceptor, change to true, and the second interceptor false to see the request flow:
Multiple Interceptor Request Flowchart:
Explanation: in conjunction with the above figure, he passed the first interceptor, opened the channel, went down, and when he reached the second intercept, he found that the channel was closed,
But it was the first way to get to the second channel, the end of the request stopped at this, unable to pass the processor, but the first interceptor has opened its channel,
So the Aftercompletion method of the final response is gone.
Test Case 2, turn on the first interceptor, change to false, and the second interceptor is true to see the request flow:
Explanation: According to the flowchart, after the first method, stop moving forward.
Test Case 3, the two channels are all open to view the request process:
SPRINGMVC's Interceptor