spring boot 拦截器

时间:2023-03-09 07:40:14
spring boot 拦截器

@SpringBootApplication
public class Application extends WebMvcConfigurerAdapter { public static void main(String[] args) {
//String[] arss= environment.getActiveProfiles();
SpringApplication.run(Application.class, args); } @Bean
public HandlerInterceptor getMyInterceptor(){
return new MyInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 多个拦截器组成一个拦截器链
// addPathPatterns 用于添加拦截规则
// excludePathPatterns 用户排除拦截
registry.addInterceptor(getMyInterceptor()).addPathPatterns("/**");
super.addInterceptors(registry);
}
package myboot.example.common;

import org.apache.naming.factory.BeanFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; /**
* Created by cxlings on 2016/7/24.
*/
public class MyInterceptor implements HandlerInterceptor { private static final Logger LOGGER = LoggerFactory.getLogger(MyInterceptor.class); @Autowired
private Environment env; public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
String ss[]=env.getActiveProfiles(); for(String a :ss){
LOGGER.info("aaa="+a);
}
String url = request.getRequestURL().toString();
String id = "2143";// request.getParameter("id");
System.out.printf(" springurl=" + url + "id=" + id);
return true;
} public void postHandle(HttpServletRequest request,
HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
} public void afterCompletion(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex)
throws Exception { } }

运行启动的命令

 java -jar myboot-1.0-SNAPSHOT.jar --spring.profiles.active=product

参考地址

http://www.bkjia.com/Javabc/1096806.html

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html
@SpringBootApplication
public class Application extends WebMvcConfigurerAdapter { public static void main(String[] args) {
//String[] arss= environment.getActiveProfiles();
SpringApplication.run(Application.class, args); } @Bean
public HandlerInterceptor getMyInterceptor(){
return new MyInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 多个拦截器组成一个拦截器链
// addPathPatterns 用于添加拦截规则
// excludePathPatterns 用户排除拦截
registry.addInterceptor(getMyInterceptor()).addPathPatterns("/**");
super.addInterceptors(registry);
}