sinat_38955460
2021-02-06 17:00
采纳率: 100%
浏览 90
已采纳

在使用zuulFilter做资源拦截,碰到无法触发自定义拦截器的问题,卡了几天了!救救孩子吧!

启动类:

@EnableZuulProxy
@SpringBootApplication
public class CrowdMainClass {
	
	public static void main(String[] args) {
		SpringApplication.run(CrowdMainClass.class, args);
	}

}

自定义过滤器:



@Component
public class CrowdAccessFilter extends ZuulFilter {

	@Override
	public boolean shouldFilter() {

		
		  // 1.获取RequestContext对象 
		RequestContext requestContext = RequestContext.getCurrentContext();
		  
		  // 2.通过RequestContext对象获取当前请求对象(框架底层是借助ThreadLocal从当前线程上获取事先绑定的Request对象)
		  HttpServletRequest request = requestContext.getRequest();
		  
		  // 3.获取servletPath值 
		  String servletPath = request.getServletPath();
		  
		  // 4.根据servletPath判断当前请求是否对应可以直接放行的特定功能 
		  boolean containsResult = AccessPassResources.PASS_RES_SET.contains(servletPath);
		  
		  if (containsResult) { 
			  
		  System.out.println("资源放行"); 
		  //5.如果当前请求是可以直接放行的特定功能请求则返回false放行 
		  return false; 
		  }
		  System.out.println("请求路径不在白名单,判断是否是静态资源");		 
		// 5.判断当前请求是否为静态资源
		// 工具方法返回true:说明当前请求是静态资源请求,取反为false表示放行不做登录检查
		// 工具方法返回false:说明当前请求不是可以放行的特定请求也不是静态资源,取反为true表示需要做登录检查
		return !AccessPassResources.judgeCurrentServletPathWetherStaticResource(servletPath);
	}

	@Override
	public Object run() throws ZuulException {

		// 1.获取当前请求对象
		RequestContext requestContext = RequestContext.getCurrentContext();
		HttpServletRequest request = requestContext.getRequest();

		// 2.获取当前Session对象
		HttpSession session = request.getSession();

		// 3.尝试从Session对象中获取已登录的用户
		Object loginMember = session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_MEMBER);
		System.out.println("获取登录用户:" + loginMember);
		// 4.判断loginMember是否为空
		if (loginMember == null) {

			// 5.从requestContext对象中获取Response对象
			HttpServletResponse response = requestContext.getResponse();

			// 6.将提示消息存入Session域
			session.setAttribute(CrowdConstant.ATTR_NAME_MESSAGE, CrowdConstant.MESSAGE_ACCESS_FORBIEDN);

			// 7.重定向到auth-consumer工程中的登录页面
			try {
				response.sendRedirect("/auth/member/to/login/page");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		System.out.println("没有重定向");
		return null;
	}

	@Override
	public String filterType() {
		// 这里返回“pre”意思是在目标微服务前执行过滤
		return "pre";
	}

	@Override
	public int filterOrder() {
		return 0;
	}

}

放行资源类:

package com.atguigu.crowd.constant;

import java.util.HashSet;
import java.util.Set;

public class AccessPassResources {
	public static final Set<String> PASS_RES_SET = new HashSet<>();
	
	static {
		PASS_RES_SET.add("/");
		PASS_RES_SET.add("/auth/member/to/reg/page");
		PASS_RES_SET.add("/auth/member/to/login/page");
		PASS_RES_SET.add("/auth/do/member/logout");
		PASS_RES_SET.add("/auth/do/member/login");
		PASS_RES_SET.add("/auth/do/member/register");
		PASS_RES_SET.add("/auth/member/send/short/message.json");
	}
	
	public static final Set<String> STATIC_RES_SET = new HashSet<>();
	
	static {
		STATIC_RES_SET.add("bootstrap");
		STATIC_RES_SET.add("css");
		STATIC_RES_SET.add("fonts");
		STATIC_RES_SET.add("img");
		STATIC_RES_SET.add("jquery");
		STATIC_RES_SET.add("layer");
		STATIC_RES_SET.add("script");
		STATIC_RES_SET.add("ztree");
	}
	
	/**
	 * 用于判断某个servletPath的值是否对应一个静态资源
	 * @param servletPath
	 * @return
	 * 		true:是静态资源
	 *  	false:不是静态资源
	 */
	public static boolean judgeCurrentServletPathWetherStaticResource(String servletPath) {
		// 1.排除字符串无效的情况
		if(servletPath == null || servletPath.length() == 0) {
			throw new RuntimeException(CrowdConstant.MESSAGE_STRING_INVALIDATE);
		}
		// 2.根据"/"拆分SerrvletPath字符串
		String[] split = servletPath.split("/");
		
		// 3.考虑到一个斜杠左边经过拆分后得到一个空字符串是数组的第一个元素,所以需要使用下标1取第二个元素
		String firstLevelPath = split[1];
		
		// 4.判断是否在集合中
		return STATIC_RES_SET.contains(firstLevelPath);
		
	}
	
}

application.yml:

server:
  port: 80
spring:
  application:
    name: syd-crowd-zuul
eureka:
  client:
    service-url:
      defaultZone: http://localhost:1000/eureka
zuul:
  ignored-services: "*"
  sensitive-headers: "*"  # 在Zuul向其他微服务重定向时保持原本头信息(请求头、响应头)
  routes:
    crowd-portal:
      service-id: syd-crowd-auth
      path: /** # 这里一定要使用两个“*”号,不然“/”路径后面的多层路径将无法访问
ribbon:
  ReadTimeout: 10000
  ConnectTimeout: 10000

日志:

2021-02-06 16:39:01.748  INFO 10312 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration' of type [org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$b31771f6] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.6.RELEASE)

2021-02-06 16:39:01.960  INFO 10312 --- [           main] com.syd.crowd.main.CrowdMainClass        : No active profile set, falling back to default profiles: default
2021-02-06 16:39:02.487  INFO 10312 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode!
2021-02-06 16:39:02.489  INFO 10312 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
2021-02-06 16:39:02.507  INFO 10312 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 8ms. Found 0 repository interfaces.
2021-02-06 16:39:02.571  WARN 10312 --- [           main] o.s.boot.actuate.endpoint.EndpointId     : Endpoint ID 'service-registry' contains invalid characters, please migrate to a valid format.
2021-02-06 16:39:02.579  WARN 10312 --- [           main] o.s.boot.actuate.endpoint.EndpointId     : Endpoint ID 'hystrix.stream' contains invalid characters, please migrate to a valid format.
2021-02-06 16:39:02.787  INFO 10312 --- [           main] o.s.cloud.context.scope.GenericScope     : BeanFactory id=2a0e37c7-5d2e-3033-86f5-7347bde53977
2021-02-06 16:39:02.977  INFO 10312 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration' of type [org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$b31771f6] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2021-02-06 16:39:03.208  INFO 10312 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 80 (http)
2021-02-06 16:39:03.228  INFO 10312 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2021-02-06 16:39:03.228  INFO 10312 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.21]
2021-02-06 16:39:03.373  INFO 10312 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2021-02-06 16:39:03.373  INFO 10312 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1402 ms
2021-02-06 16:39:03.470  WARN 10312 --- [           main] c.n.c.sources.URLConfigurationSource     : No URLs will be polled as dynamic configuration sources.
2021-02-06 16:39:03.470  INFO 10312 --- [           main] c.n.c.sources.URLConfigurationSource     : To enable URLs as dynamic configuration sources, define System property archaius.configurationSource.additionalUrls or make config.properties available on classpath.
2021-02-06 16:39:03.480  INFO 10312 --- [           main] c.netflix.config.DynamicPropertyFactory  : DynamicPropertyFactory is initialized with configuration sources: com.netflix.config.ConcurrentCompositeConfiguration@bb6f3f7
2021-02-06 16:39:04.478  WARN 10312 --- [           main] c.n.c.sources.URLConfigurationSource     : No URLs will be polled as dynamic configuration sources.
2021-02-06 16:39:04.478  INFO 10312 --- [           main] c.n.c.sources.URLConfigurationSource     : To enable URLs as dynamic configuration sources, define System property archaius.configurationSource.additionalUrls or make config.properties available on classpath.
2021-02-06 16:39:04.668  INFO 10312 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2021-02-06 16:39:05.008  INFO 10312 --- [           main] io.lettuce.core.EpollProvider            : Starting without optional epoll library
2021-02-06 16:39:05.009  INFO 10312 --- [           main] io.lettuce.core.KqueueProvider           : Starting without optional kqueue library
2021-02-06 16:39:05.543  INFO 10312 --- [           main] o.s.c.n.zuul.ZuulFilterInitializer       : Starting filter initializer
2021-02-06 16:39:05.558  INFO 10312 --- [           main] o.s.b.a.e.web.EndpointLinksResolver      : Exposing 2 endpoint(s) beneath base path '/actuator'
2021-02-06 16:39:05.624  INFO 10312 --- [           main] o.s.c.n.eureka.InstanceInfoFactory       : Setting initial instance status as: STARTING
2021-02-06 16:39:05.676  INFO 10312 --- [           main] com.netflix.discovery.DiscoveryClient    : Initializing Eureka in region us-east-1
2021-02-06 16:39:05.729  INFO 10312 --- [           main] c.n.d.provider.DiscoveryJerseyProvider   : Using JSON encoding codec LegacyJacksonJson
2021-02-06 16:39:05.729  INFO 10312 --- [           main] c.n.d.provider.DiscoveryJerseyProvider   : Using JSON decoding codec LegacyJacksonJson
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by com.thoughtworks.xstream.core.util.Fields (file:/C:/Users/86911/.m2/repository/com/thoughtworks/xstream/xstream/1.4.10/xstream-1.4.10.jar) to field java.util.TreeMap.comparator
WARNING: Please consider reporting this to the maintainers of com.thoughtworks.xstream.core.util.Fields
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
2021-02-06 16:39:05.861  INFO 10312 --- [           main] c.n.d.provider.DiscoveryJerseyProvider   : Using XML encoding codec XStreamXml
2021-02-06 16:39:05.861  INFO 10312 --- [           main] c.n.d.provider.DiscoveryJerseyProvider   : Using XML decoding codec XStreamXml
2021-02-06 16:39:06.103  INFO 10312 --- [           main] c.n.d.s.r.aws.ConfigClusterResolver      : Resolving eureka endpoints via configuration
2021-02-06 16:39:06.132  INFO 10312 --- [           main] com.netflix.discovery.DiscoveryClient    : Disable delta property : false
2021-02-06 16:39:06.132  INFO 10312 --- [           main] com.netflix.discovery.DiscoveryClient    : Single vip registry refresh property : null
2021-02-06 16:39:06.132  INFO 10312 --- [           main] com.netflix.discovery.DiscoveryClient    : Force full registry fetch : false
2021-02-06 16:39:06.132  INFO 10312 --- [           main] com.netflix.discovery.DiscoveryClient    : Application is null : false
2021-02-06 16:39:06.133  INFO 10312 --- [           main] com.netflix.discovery.DiscoveryClient    : Registered Applications size is zero : true
2021-02-06 16:39:06.133  INFO 10312 --- [           main] com.netflix.discovery.DiscoveryClient    : Application version is -1: true
2021-02-06 16:39:06.133  INFO 10312 --- [           main] com.netflix.discovery.DiscoveryClient    : Getting all instance registry info from the eureka server
2021-02-06 16:39:06.202  INFO 10312 --- [on(1)-127.0.0.1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2021-02-06 16:39:06.202  INFO 10312 --- [on(1)-127.0.0.1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2021-02-06 16:39:06.212  INFO 10312 --- [on(1)-127.0.0.1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 10 ms
2021-02-06 16:39:06.255  INFO 10312 --- [           main] com.netflix.discovery.DiscoveryClient    : The response status is 200
2021-02-06 16:39:06.260  INFO 10312 --- [           main] com.netflix.discovery.DiscoveryClient    : Starting heartbeat executor: renew interval is: 30
2021-02-06 16:39:06.266  INFO 10312 --- [           main] c.n.discovery.InstanceInfoReplicator     : InstanceInfoReplicator onDemand update allowed rate per min is 4
2021-02-06 16:39:06.278  INFO 10312 --- [           main] com.netflix.discovery.DiscoveryClient    : Discovery Client initialized at timestamp 1612600746277 with initial instances count: 3
2021-02-06 16:39:06.280  INFO 10312 --- [           main] o.s.c.n.e.s.EurekaServiceRegistry        : Registering application SYD-CROWD-ZUUL with eureka with status UP
2021-02-06 16:39:06.281  INFO 10312 --- [           main] com.netflix.discovery.DiscoveryClient    : Saw local status change event StatusChangeEvent [timestamp=1612600746281, current=UP, previous=STARTING]
2021-02-06 16:39:06.282  INFO 10312 --- [nfoReplicator-0] com.netflix.discovery.DiscoveryClient    : DiscoveryClient_SYD-CROWD-ZUUL/192.168.106.37:syd-crowd-zuul:80: registering service...
2021-02-06 16:39:06.297  INFO 10312 --- [nfoReplicator-0] com.netflix.discovery.DiscoveryClient    : DiscoveryClient_SYD-CROWD-ZUUL/192.168.106.37:syd-crowd-zuul:80 - registration status: 204
2021-02-06 16:39:06.856  INFO 10312 --- [           main] s.a.ScheduledAnnotationBeanPostProcessor : No TaskScheduler/ScheduledExecutorService bean found for scheduled processing
2021-02-06 16:39:06.876  INFO 10312 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 80 (http) with context path ''
2021-02-06 16:39:06.876  INFO 10312 --- [           main] .s.c.n.e.s.EurekaAutoServiceRegistration : Updating port to 80
2021-02-06 16:39:06.878  INFO 10312 --- [           main] com.syd.crowd.main.CrowdMainClass        : Started CrowdMainClass in 5.704 seconds (JVM running for 6.412)
2021-02-06 16:42:07.836  INFO 10312 --- [p-nio-80-exec-1] c.netflix.config.ChainedDynamicProperty  : Flipping property: syd-crowd-auth.ribbon.ActiveConnectionsLimit to use NEXT property: niws.loadbalancer.availabilityFilteringRule.activeConnectionsLimit = 2147483647
2021-02-06 16:42:07.861  INFO 10312 --- [p-nio-80-exec-1] c.n.u.concurrent.ShutdownEnabledTimer    : Shutdown hook installed for: NFLoadBalancer-PingTimer-syd-crowd-auth
2021-02-06 16:42:07.861  INFO 10312 --- [p-nio-80-exec-1] c.netflix.loadbalancer.BaseLoadBalancer  : Client: syd-crowd-auth instantiated a LoadBalancer: DynamicServerListLoadBalancer:{NFLoadBalancer:name=syd-crowd-auth,current list of Servers=[],Load balancer stats=Zone stats: {},Server stats: []}ServerList:null
2021-02-06 16:42:07.873  INFO 10312 --- [p-nio-80-exec-1] c.n.l.DynamicServerListLoadBalancer      : Using serverListUpdater PollingServerListUpdater
2021-02-06 16:42:07.892  INFO 10312 --- [p-nio-80-exec-1] c.netflix.config.ChainedDynamicProperty  : Flipping property: syd-crowd-auth.ribbon.ActiveConnectionsLimit to use NEXT property: niws.loadbalancer.availabilityFilteringRule.activeConnectionsLimit = 2147483647
2021-02-06 16:42:07.896  INFO 10312 --- [p-nio-80-exec-1] c.n.l.DynamicServerListLoadBalancer      : DynamicServerListLoadBalancer for client syd-crowd-auth initialized: DynamicServerListLoadBalancer:{NFLoadBalancer:name=syd-crowd-auth,current list of Servers=[192.168.106.37:4000],Load balancer stats=Zone stats: {defaultzone=[Zone:defaultzone;	Instance count:1;	Active connections count: 0;	Circuit breaker tripped count: 0;	Active connections per server: 0.0;]
},Server stats: [[Server:192.168.106.37:4000;	Zone:defaultZone;	Total Requests:0;	Successive connection failure:0;	Total blackout seconds:0;	Last connection made:Thu Jan 01 08:00:00 CST 1970;	First connection made: Thu Jan 01 08:00:00 CST 1970;	Active Connections:0;	total failure count in last (1000) msecs:0;	average resp time:0.0;	90 percentile resp time:0.0;	95 percentile resp time:0.0;	min resp time:0.0;	max resp time:0.0;	stddev resp time:0.0]
]}ServerList:org.springframework.cloud.netflix.ribbon.eureka.DomainExtractingServerList@15c45a5d
2021-02-06 16:42:08.875  INFO 10312 --- [erListUpdater-0] c.netflix.config.ChainedDynamicProperty  : Flipping property: syd-crowd-auth.ribbon.ActiveConnectionsLimit to use NEXT property: niws.loadbalancer.availabilityFilteringRule.activeConnectionsLimit = 2147483647
2021-02-06 16:44:06.137  INFO 10312 --- [trap-executor-0] c.n.d.s.r.aws.ConfigClusterResolver      : Resolving eureka endpoints via configuration
2021-02-06 16:49:06.139  INFO 10312 --- [trap-executor-0] c.n.d.s.r.aws.ConfigClusterResolver      : Resolving eureka endpoints via configuration
2021-02-06 16:54:06.139  INFO 10312 --- [trap-executor-0] c.n.d.s.r.aws.ConfigClusterResolver      : Resolving eureka endpoints via configuration

看日志并没有通过我的自定义过滤器进行请求拦截,启动类的@EnabltZuulProxy也标注了,看不出哪里有问题.求助!

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

相关推荐 更多相似问题