其他分享
首页 > 其他分享> > spring-Interception

spring-Interception

作者:互联网

拦截器

拦截器&过滤器

拦截器执行流程

---perHandle --->return----->controller----->postHandle---->afterCompletion----->

---->false---------------------------跳过这一环了-------------------------->

代码

package com.yang.controller.Interception;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class ProjectInterception implements HandlerInterceptor {
   @Override
   public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       System.out.println("preHandle...");
       return true;
  }

   @Override
   public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
       System.out.println("postHandle...");

  }

   @Override
   public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
       System.out.println("afterCompletion...");

  }
}
package com.yang.config;

import com.yang.controller.Interception.ProjectInterception;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
@Configuration
public class SpringMvcSupport extends WebMvcConfigurationSupport {
   @Autowired
   private ProjectInterception projectInterception;

   @Override
   protected void addResourceHandlers(ResourceHandlerRegistry registry) {
       registry.addResourceHandler("/pages/**").addResourceLocations("/pages/");
  }

   @Override
   protected void addInterceptors(InterceptorRegistry registry) {
       registry.addInterceptor(projectInterception).addPathPatterns("/books");
  }
}
package com.yang.config;


import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

@Configuration
@ComponentScan({"com.yang.controller","com.yang.config"})
@EnableWebMvc//开启接受json
public class SpringMvcConfig {
}

配置拦截器链

标签:spring,Interception,springframework,import,org,config,servlet,annotation
来源: https://www.cnblogs.com/yzlworld/p/16500274.html