org.springframework.web.servlet.handler.HandlerInterceptorAdapter Java Examples

The following examples show how to use org.springframework.web.servlet.handler.HandlerInterceptorAdapter. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RequestMappingInfoHandlerMappingTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void getHandlerMappedInterceptors() throws Exception {
	String path = "/foo";
	HandlerInterceptor interceptor = new HandlerInterceptorAdapter() {};
	MappedInterceptor mappedInterceptor = new MappedInterceptor(new String[] {path}, interceptor);

	TestRequestMappingInfoHandlerMapping mapping = new TestRequestMappingInfoHandlerMapping();
	mapping.registerHandler(new TestController());
	mapping.setInterceptors(new Object[] { mappedInterceptor });
	mapping.setApplicationContext(new StaticWebApplicationContext());

	HandlerExecutionChain chain = mapping.getHandler(new MockHttpServletRequest("GET", path));
	assertNotNull(chain);
	assertNotNull(chain.getInterceptors());
	assertSame(interceptor, chain.getInterceptors()[0]);

	chain = mapping.getHandler(new MockHttpServletRequest("GET", "/invalid"));
	assertNull(chain);
}
 
Example #2
Source File: RequestMappingInfoHandlerMappingTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void getHandlerMappedInterceptors() throws Exception {
	String path = "/foo";
	HandlerInterceptor interceptor = new HandlerInterceptorAdapter() {};
	MappedInterceptor mappedInterceptor = new MappedInterceptor(new String[] {path}, interceptor);

	TestRequestMappingInfoHandlerMapping mapping = new TestRequestMappingInfoHandlerMapping();
	mapping.registerHandler(new TestController());
	mapping.setInterceptors(new Object[] { mappedInterceptor });
	mapping.setApplicationContext(new StaticWebApplicationContext());

	HandlerExecutionChain chain = mapping.getHandler(new MockHttpServletRequest("GET", path));
	assertNotNull(chain);
	assertNotNull(chain.getInterceptors());
	assertSame(interceptor, chain.getInterceptors()[0]);

	chain = mapping.getHandler(new MockHttpServletRequest("GET", "/invalid"));
	assertNull(chain);
}
 
Example #3
Source File: HswebAutoConfiguration.java    From hsweb-framework with Apache License 2.0 6 votes vote down vote up
@Bean
public WebMvcConfigurer webMvcConfigurer(List<HandlerMethodArgumentResolver> handlerMethodArgumentResolvers) {
    return new WebMvcConfigurerAdapter() {
        @Override
        public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
            super.addArgumentResolvers(argumentResolvers);
            argumentResolvers.addAll(handlerMethodArgumentResolvers);
        }

        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(new HandlerInterceptorAdapter() {
                @Override
                public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
                    //clear thread local
                    ThreadLocalUtils.clear();
                }
            });
        }
    };
}
 
Example #4
Source File: RequestMappingInfoHandlerMappingTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void mappedInterceptors() throws Exception {
	String path = "/foo";
	HandlerInterceptor interceptor = new HandlerInterceptorAdapter() {};
	MappedInterceptor mappedInterceptor = new MappedInterceptor(new String[] {path}, interceptor);

	TestRequestMappingInfoHandlerMapping hm = new TestRequestMappingInfoHandlerMapping();
	hm.registerHandler(new TestController());
	hm.setInterceptors(new Object[] { mappedInterceptor });
	hm.setApplicationContext(new StaticWebApplicationContext());

	HandlerExecutionChain chain = hm.getHandler(new MockHttpServletRequest("GET", path));
	assertNotNull(chain);
	assertNotNull(chain.getInterceptors());
	assertSame(interceptor, chain.getInterceptors()[0]);

	chain = hm.getHandler(new MockHttpServletRequest("GET", "/invalid"));
	assertNull(chain);
}
 
Example #5
Source File: WebConfig.java    From spring-boot-samples with Apache License 2.0 6 votes vote down vote up
@Override
public void addInterceptors(InterceptorRegistry registry) {
	registry.addInterceptor(new HandlerInterceptorAdapter() {
		@Override
		public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
				ModelAndView modelAndView) throws Exception {

			if (handler instanceof HandlerMethod) {
				HandlerMethod handlerMethod = (HandlerMethod) handler;
				Navigation navSection = handlerMethod.getBean().getClass().getAnnotation(Navigation.class);
				if (navSection != null && modelAndView != null) {
					modelAndView.addObject("navSection", navSection.value().toString().toLowerCase());
				}
			}
		}
	});
}
 
Example #6
Source File: ResourceServerTokenRelayAutoConfiguration.java    From spring-cloud-security with Apache License 2.0 6 votes vote down vote up
@Override
public void addInterceptors(InterceptorRegistry registry) {
	registry.addInterceptor(

			new HandlerInterceptorAdapter() {
				@Override
				public boolean preHandle(HttpServletRequest request,
						HttpServletResponse response, Object handler)
						throws Exception {
					accessTokenContextRelay.copyToken();
					return true;
				}
			}

	);
}
 
Example #7
Source File: WebMvcConfig.java    From feiqu-opensource with Apache License 2.0 5 votes vote down vote up
/**
 * 添加拦截器
 */
@Override
public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(new HandlerInterceptorAdapter() {
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                                 Object handler) throws Exception {

            //如果不是ajax 代表是点击页面 则统计点击数量
            if (null == request.getHeader("X-Requested-With") || !request.getHeader("X-Requested-With").equalsIgnoreCase("XMLHttpRequest")) {
                try {
                    String ip = WebUtil.getIP(request);
                    JedisCommands commands = JedisProviderFactory.getJedisCommands(null);
                    boolean isBlackIp = commands.sismember(CommonConstant.FQ_BLACK_LIST_REDIS_KEY,ip);
                    if(isBlackIp){
                        logger.info("该ip:{} 存在于黑名单,禁止其访问!",ip);
                        response.sendRedirect(request.getContextPath()+"/blackList/denyService");
                        return false;
                    }

                    String clickkey = CommonConstant.FQ_IP_DATA_THIS_DAY_FORMAT;
                    Double score = commands.zscore(clickkey,ip);
                    if(score == null){
                        commands.zadd(clickkey,1,ip);
                    }else {
                        commands.zadd(clickkey,score+1,ip);
                    }
                    commands.expire(clickkey,30*24*60*60);//存放一个月
                } finally{
                    JedisProviderFactory.getJedisProvider(null).release();
                }
            }
            return true;
        }
    }).addPathPatterns("/**").excludePathPatterns("/blackList/denyService");
}
 
Example #8
Source File: MvcConfigurer.java    From spring-boot-api-project-seed with Apache License 2.0 5 votes vote down vote up
/**
 * 添加拦截器
 *
 * @param interceptorRegistry
 */
@Override
public void addInterceptors(InterceptorRegistry interceptorRegistry) {
    //跨域拦截
    interceptorRegistry.addInterceptor(allowCrossDomainInterceptor).addPathPatterns(apiUri);
    //响应结果控制拦截
    interceptorRegistry.addInterceptor(responseResultInterceptor).addPathPatterns(apiUri);
    //接口签名认证拦截器,该签名认证比较简单,实际项目中可以使用Json Web Token或其他更好的方式替代。
    //开发环境忽略签名认证
    if (!"dev".equals(env)) {
        interceptorRegistry.addInterceptor(new HandlerInterceptorAdapter() {
            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
                //验证签名
                boolean pass = validateSign(request);
                if (pass) {
                    return true;
                } else {
                    logger.warn("签名认证失败,请求接口:{},请求IP:{},请求参数:{}",
                            request.getRequestURI(), IpUtil.getRealIp(request), JSON.toJSONString(request.getParameterMap()));
                    PlatformResult result = new PlatformResult();
                    result.setCode(HttpStatus.UNAUTHORIZED.value()).setMessage("签名认证失败");
                    responseResult(response, result);
                    return false;
                }
            }
        });
    }
}