Interceptor拦截器demo
##接口测试类
@RestController
public class TestController {
@RequestMapping(value = "/myInterceptorsTestUrl", method = RequestMethod.GET)
public String myInterceptorsTestUrl(HttpServletRequest request) {
return request.getRequestURL().toString() +"-"+ request.getAttribute("name");
}
@RequestMapping(value = "/testUrl", method = RequestMethod.GET)
public String testUrl(HttpServletRequest request) {
return request.getRequestURL().toString() +"-"+ request.getAttribute("name");
}
}
##拦截器类
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyInterceptor implements HandlerInterceptor {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("preHandle>>>拦截器");
//设置编码
request.setCharacterEncoding("UTF-8");
//设置属性值
request.setAttribute("name","hello,interceptor");
//参数
String path = request.getRequestURI();
String reqMethod = request.getMethod();
HandlerMethod hm = (HandlerMethod) handler;
String userAgent = request.getHeader("User-Agent");
String reqIp = getReqIpAddr(request);
String reqUri = request.getServletPath();
System.out.println("path=" + path);
System.out.println("reqMethod=" + reqMethod);
System.out.println("userAgent=" + userAgent);
System.out.println("reqIp=" + reqIp);
System.out.println("reqUri=" + reqUri);
//调用
// hm.getMethod().invoke(hm);
String methodName = hm.getMethod().getName();
System.out.println("methodName=" + methodName);
String beanName = hm.getBeanType().getName();
System.out.println("beanName=" + beanName);
return true; //return false; 不往后续执行
}
protected String getReqIpAddr(HttpServletRequest request) {
String ip = null;
try {
ip = request.getHeader("x-forwarded-for");
if (!StringUtils.hasText(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (!StringUtils.hasText(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (!StringUtils.hasText(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
} catch (Exception e) {
logger.error("",e);
}
return ip;
}
@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>>>拦截器");
}
}
//拦截器注册类
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.ArrayList;
import java.util.List;
@Configuration
public class WebAPPMvcConfigurer implements WebMvcConfigurer {
/**
* 拦截器注册
* @param registry
*
* http://localhost:8080/testUrl
* 页面输出:http://localhost:8080/testUrl-null
*
* http://localhost:8080/myInterceptorsTestUrl
* 页面输出:http://localhost:8080/myInterceptorsTestUrl-hello,interceptor
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
//匹配规则
// registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**");
//按请求地址来匹配,字符集合
List<String> listPath = new ArrayList<>();
listPath.add("/myInterceptorsTestUrl");
registry.addInterceptor(new MyInterceptor()).addPathPatterns(listPath);
}
}
或者在applicationContext.xml配置文件中配置
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/myInterceptorsTestUrl"/>
<bean class="com.example.mytest.interceptor.MyInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
</beans>
//springboot启动类加载配置文件
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.ImportResource;
@EnableAspectJAutoProxy
@SpringBootApplication
@ImportResource("classpath:applicationContext.xml")
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}