Spring interceptors
- An application of Spring Aop that executes a piece of code to enhance an existing method without modifying the source code.
The sample
- Implement the HandlerInterceptor interface
public class InterceptorT implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("========= before reaching controller ==============");
return true;/ / return true on them
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("=========== after controller ============");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("============= after receiving everything, clean it up ============"); }}Copy the code
- Configure the spring
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/ * *"/><! -- Intercept all requests -->
<bean class="com.mvc.interceptor.InterceptorT"/>
</mvc:interceptor>
</mvc:interceptors>
Copy the code
- test
@Controller
public class InterceptorController {
@RequestMapping("/t")
@ResponseBody
public String test(a){
System.out.println("From the controller");
return "From the controller"; }}Copy the code