org.springframework.web.servlet.HandlerInterceptor Java Examples

The following examples show how to use org.springframework.web.servlet.HandlerInterceptor. 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: InterceptorInjectorTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
public void testShouldJustReturnInterceptorsOfFrameworkIfNoTabInterceptors() throws Throwable {
    HandlerInterceptor interceptorOfFramework = new HandlerInterceptorSub();
    HandlerInterceptor[] interceptorsOfFramework = new HandlerInterceptor[] {interceptorOfFramework};

    ProceedingJoinPoint proceedingJoinPoint = mock(ProceedingJoinPoint.class);
    when(proceedingJoinPoint.proceed()).thenReturn(new HandlerExecutionChain(null, null));
    InterceptorInjector injector = new InterceptorInjector();
    injector.setInterceptors(interceptorsOfFramework);

    HandlerExecutionChain handlers =
            injector.mergeInterceptorsToTabs(proceedingJoinPoint);

    Assert.assertEquals(1, handlers.getInterceptors().length);
    Assert.assertSame(interceptorOfFramework, handlers.getInterceptors()[0]);
}
 
Example #2
Source File: InterceptorRegistryTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
private List<HandlerInterceptor> getInterceptorsForPath(String lookupPath) {
	PathMatcher pathMatcher = new AntPathMatcher();
	List<HandlerInterceptor> result = new ArrayList<HandlerInterceptor>();
	for (Object interceptor : this.registry.getInterceptors()) {
		if (interceptor instanceof MappedInterceptor) {
			MappedInterceptor mappedInterceptor = (MappedInterceptor) interceptor;
			if (mappedInterceptor.matches(lookupPath, pathMatcher)) {
				result.add(mappedInterceptor.getInterceptor());
			}
		}
		else if (interceptor instanceof HandlerInterceptor) {
			result.add((HandlerInterceptor) interceptor);
		}
		else {
			fail("Unexpected interceptor type: " + interceptor.getClass().getName());
		}
	}
	return result;
}
 
Example #3
Source File: IntercepterAnnotationHandlerMapping.java    From onboard with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
private List<HandlerInterceptor> getHandlerInterceptors(Class<? extends Object> clazz,
        Interceptors interceptorAnnotation) {
    List<HandlerInterceptor> interceptors = new ArrayList<HandlerInterceptor>();

    if (interceptorAnnotation != null) {
        Class[] interceptorClasses = interceptorAnnotation.value();
        if (interceptorClasses != null) {
            for (Class interceptorClass : interceptorClasses) {
                if (!HandlerInterceptor.class.isAssignableFrom(interceptorClass)) {
                    raiseIllegalInterceptorValue(clazz, interceptorClass);
                }
                interceptors.add((HandlerInterceptor) getApplicationContext().getBean(interceptorClass));
            }
        }
    }

    return interceptors;
}
 
Example #4
Source File: BootMvcConfigurerAdapter.java    From onetwo with Apache License 2.0 6 votes vote down vote up
@Override
	public void addInterceptors(InterceptorRegistry registry) {
		/*Optional.ofNullable(interceptorList).ifPresent(list->{
			list.stream().forEach(inter->registry.addInterceptor(inter));
		});*/
		if(LangUtils.isEmpty(interceptorList)){
			return ;
		}
		for(HandlerInterceptor inter : interceptorList){
			InterceptorRegistration reg = registry.addInterceptor(inter);
			if(inter instanceof WebInterceptorAdapter){
				WebInterceptorAdapter webinter = (WebInterceptorAdapter) inter;
				if(LangUtils.isEmpty(webinter.getPathPatterns())){
					continue;
				}
				reg.addPathPatterns(webinter.getPathPatterns());
			}
		}
//		registry.addInterceptor(new BootFirstInterceptor());
	}
 
Example #5
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 #6
Source File: WebMvcConfigurationSupport.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Return a handler mapping ordered at Integer.MAX_VALUE-1 with mapped
 * resource handlers. To configure resource handling, override
 * {@link #addResourceHandlers}.
 */
@Bean
public HandlerMapping resourceHandlerMapping() {
	ResourceHandlerRegistry registry = new ResourceHandlerRegistry(this.applicationContext, this.servletContext);
	addResourceHandlers(registry);

	AbstractHandlerMapping handlerMapping = registry.getHandlerMapping();
	if (handlerMapping != null) {
		handlerMapping.setPathMatcher(mvcPathMatcher());
		handlerMapping.setUrlPathHelper(mvcUrlPathHelper());
		handlerMapping.setInterceptors(new HandlerInterceptor[] {
				new ResourceUrlProviderExposingInterceptor(mvcResourceUrlProvider())});
		handlerMapping.setCorsConfigurations(getCorsConfigurations());
	}
	else {
		handlerMapping = new EmptyHandlerMapping();
	}
	return handlerMapping;
}
 
Example #7
Source File: InterceptorRegistryTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
private List<HandlerInterceptor> getInterceptorsForPath(String lookupPath) {
	PathMatcher pathMatcher = new AntPathMatcher();
	List<HandlerInterceptor> result = new ArrayList<>();
	for (Object interceptor : this.registry.getInterceptors()) {
		if (interceptor instanceof MappedInterceptor) {
			MappedInterceptor mappedInterceptor = (MappedInterceptor) interceptor;
			if (mappedInterceptor.matches(lookupPath, pathMatcher)) {
				result.add(mappedInterceptor.getInterceptor());
			}
		}
		else if (interceptor instanceof HandlerInterceptor) {
			result.add((HandlerInterceptor) interceptor);
		}
		else {
			fail("Unexpected interceptor type: " + interceptor.getClass().getName());
		}
	}
	return result;
}
 
Example #8
Source File: SpringMvcPolyfill.java    From Milkomeda with MIT License 6 votes vote down vote up
/**
 * 动态删除拦截器
 * @param interceptor       HandlerInterceptor
 * @param handlerMapping    AbstractHandlerMapping实现类
 */
@SuppressWarnings("all")
public static void removeDynamicInterceptor(HandlerInterceptor interceptor, AbstractHandlerMapping handlerMapping) {
    if (interceptor == null) return;
    try {
        findAdaptedInterceptorsField(handlerMapping);
        List<HandlerInterceptor> handlerInterceptors = (List<HandlerInterceptor>) adaptedInterceptorsField.get(handlerMapping);
        List<HandlerInterceptor> shouldRemoveInterceptors = handlerInterceptors.stream().filter(itor -> {
            // 只判断映射的拦截器类型
            if (itor instanceof HydrogenMappedInterceptor) {
                return itor.equals(interceptor);
            }
            return false;
        }).collect(Collectors.toList());
        handlerInterceptors.removeAll(shouldRemoveInterceptors);
        adaptedInterceptorsField.set(handlerMapping, handlerInterceptors);
    } catch (Exception e) {
        log.error("SpringMvcPolyfill invoke AbstractHandlerMapping.adaptedInterceptors error with msg: {}",  e.getMessage(), e);
    }
}
 
Example #9
Source File: PrintingResultHandler.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Print the handler.
 */
protected void printHandler(@Nullable Object handler, @Nullable HandlerInterceptor[] interceptors)
		throws Exception {

	if (handler == null) {
		this.printer.printValue("Type", null);
	}
	else {
		if (handler instanceof HandlerMethod) {
			HandlerMethod handlerMethod = (HandlerMethod) handler;
			this.printer.printValue("Type", handlerMethod.getBeanType().getName());
			this.printer.printValue("Method", handlerMethod);
		}
		else {
			this.printer.printValue("Type", handler.getClass().getName());
		}
	}
}
 
Example #10
Source File: InterceptorInjectorTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
public void testShouldMergeInterceptors() throws Throwable {
    HandlerInterceptor interceptorOfFramework = new HandlerInterceptorSub();
    HandlerInterceptor interceptorOfTab = new HandlerInterceptorSub();
    HandlerInterceptor[] interceptorsOfFramework = new HandlerInterceptor[] {interceptorOfFramework};
    HandlerInterceptor[] interceptorsOfTab = new HandlerInterceptor[] {interceptorOfTab};

    ProceedingJoinPoint proceedingJoinPoint = mock(ProceedingJoinPoint.class);
    when(proceedingJoinPoint.proceed()).thenReturn(new HandlerExecutionChain(null, interceptorsOfTab));

    InterceptorInjector injector = new InterceptorInjector();
    injector.setInterceptors(interceptorsOfFramework);

    HandlerExecutionChain handlers =
            injector.mergeInterceptorsToTabs(proceedingJoinPoint);

    Assert.assertEquals(2, handlers.getInterceptors().length);
    Assert.assertSame(interceptorOfFramework, handlers.getInterceptors()[0]);
    Assert.assertSame(interceptorOfTab, handlers.getInterceptors()[1]);
}
 
Example #11
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 #12
Source File: PrintingResultHandler.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Print the handler.
 */
protected void printHandler(@Nullable Object handler, @Nullable HandlerInterceptor[] interceptors)
		throws Exception {

	if (handler == null) {
		this.printer.printValue("Type", null);
	}
	else {
		if (handler instanceof HandlerMethod) {
			HandlerMethod handlerMethod = (HandlerMethod) handler;
			this.printer.printValue("Type", handlerMethod.getBeanType().getName());
			this.printer.printValue("Method", handlerMethod);
		}
		else {
			this.printer.printValue("Type", handler.getClass().getName());
		}
	}
}
 
Example #13
Source File: AbsController.java    From jeesupport with MIT License 6 votes vote down vote up
/**
 * 拦截器,只有AbsControllerConfig被继承,且被扫描到后生效。
 *
 * @return
 */
@Bean
public HandlerInterceptor handlerInterceptor(){
    log.debug( "--应用AbsControllerConfing拦截器。" );
    return new HandlerInterceptor(){
        @Override
        public boolean preHandle( HttpServletRequest _request, HttpServletResponse _response, Object _handler ) throws IOException{
            String uri = UrlUtil.uri2mapping( _request.getRequestURI() );

            templateService.loadTemplate( uri, _request );
            superService.loadUserMenus( _request );
            superService.loadUserBreadcrumb( _request );
            superService.loadUserActiveMenus( _request );
            return true;
        }
    };
}
 
Example #14
Source File: StubMvcResult.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
public StubMvcResult(MockHttpServletRequest request,
					 Object handler,
					 HandlerInterceptor[] interceptors,
					 Exception resolvedException,
					 ModelAndView mav,
					 FlashMap flashMap,
					 MockHttpServletResponse response) {
	this.request = request;
	this.handler = handler;
	this.interceptors = interceptors;
	this.resolvedException = resolvedException;
	this.mav = mav;
	this.flashMap = flashMap;
	this.response = response;
}
 
Example #15
Source File: InterceptorRegistryTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void addTwoInterceptors() {
	this.registry.addInterceptor(this.interceptor1);
	this.registry.addInterceptor(this.interceptor2);
	List<HandlerInterceptor> interceptors = getInterceptorsForPath(null);
	assertEquals(Arrays.asList(this.interceptor1, this.interceptor2), interceptors);
}
 
Example #16
Source File: MappedInterceptorTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void preHandle() throws Exception {
	HandlerInterceptor interceptor = mock(HandlerInterceptor.class);
	MappedInterceptor mappedInterceptor = new MappedInterceptor(new String[] { "/**" }, interceptor);
	mappedInterceptor.preHandle(mock(HttpServletRequest.class), mock(HttpServletResponse.class), null);

	then(interceptor).should().preHandle(any(HttpServletRequest.class), any(HttpServletResponse.class), any());
}
 
Example #17
Source File: HttpRequestInterceptor.java    From yue-library with Apache License 2.0 5 votes vote down vote up
/**
 * 在控制器(controller方法)执行之后,视图渲染之前
 */
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
		ModelAndView modelAndView) throws Exception {
	// TODO Auto-generated method stub
	HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
}
 
Example #18
Source File: MappedInterceptorTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void afterCompletion() throws Exception {
	HandlerInterceptor interceptor = mock(HandlerInterceptor.class);
	MappedInterceptor mappedInterceptor = new MappedInterceptor(new String[] { "/**" }, interceptor);
	mappedInterceptor.afterCompletion(mock(HttpServletRequest.class), mock(HttpServletResponse.class),
			null, mock(Exception.class));

	then(interceptor).should().afterCompletion(any(), any(), any(), any());
}
 
Example #19
Source File: SimpleUrlHandlerMappingTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
private HandlerExecutionChain getHandler(HandlerMapping hm, MockHttpServletRequest req) throws Exception {
	HandlerExecutionChain hec = hm.getHandler(req);
	HandlerInterceptor[] interceptors = hec.getInterceptors();
	if (interceptors != null) {
		for (HandlerInterceptor interceptor : interceptors) {
			interceptor.preHandle(req, null, hec.getHandler());
		}
	}
	return hec;
}
 
Example #20
Source File: InterceptorRegistryTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void addWebRequestInterceptorsWithUrlPatterns() throws Exception {
	this.registry.addWebRequestInterceptor(this.webInterceptor1).addPathPatterns("/path1");
	this.registry.addWebRequestInterceptor(this.webInterceptor2).addPathPatterns("/path2");

	List<HandlerInterceptor> interceptors = getInterceptorsForPath("/path1");
	assertEquals(1, interceptors.size());
	verifyWebInterceptor(interceptors.get(0), this.webInterceptor1);

	interceptors = getInterceptorsForPath("/path2");
	assertEquals(1, interceptors.size());
	verifyWebInterceptor(interceptors.get(0), this.webInterceptor2);
}
 
Example #21
Source File: HandlerMappingIntrospector.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public CorsConfiguration getCorsConfiguration(HttpServletRequest request) {
	Assert.notNull(this.handlerMappings, "Handler mappings not initialized");
	HttpServletRequest wrapper = new RequestAttributeChangeIgnoringWrapper(request);
	for (HandlerMapping handlerMapping : this.handlerMappings) {
		HandlerExecutionChain handler = null;
		try {
			handler = handlerMapping.getHandler(wrapper);
		}
		catch (Exception ex) {
			// Ignore
		}
		if (handler == null) {
			continue;
		}
		if (handler.getInterceptors() != null) {
			for (HandlerInterceptor interceptor : handler.getInterceptors()) {
				if (interceptor instanceof CorsConfigurationSource) {
					return ((CorsConfigurationSource) interceptor).getCorsConfiguration(wrapper);
				}
			}
		}
		if (handler.getHandler() instanceof CorsConfigurationSource) {
			return ((CorsConfigurationSource) handler.getHandler()).getCorsConfiguration(wrapper);
		}
	}
	return null;
}
 
Example #22
Source File: StandaloneMockMvcBuilder.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Add interceptors mapped to a set of path patterns.
 */
public StandaloneMockMvcBuilder addMappedInterceptors(
		@Nullable String[] pathPatterns, HandlerInterceptor... interceptors) {

	for (HandlerInterceptor interceptor : interceptors) {
		this.mappedInterceptors.add(new MappedInterceptor(pathPatterns, interceptor));
	}
	return this;
}
 
Example #23
Source File: AbstractHandlerMapping.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Return all configured {@link MappedInterceptor}s as an array.
 * @return the array of {@link MappedInterceptor}s, or {@code null} if none
 */
protected final MappedInterceptor[] getMappedInterceptors() {
	List<MappedInterceptor> mappedInterceptors = new ArrayList<MappedInterceptor>();
	for (HandlerInterceptor interceptor : this.adaptedInterceptors) {
		if (interceptor instanceof MappedInterceptor) {
			mappedInterceptors.add((MappedInterceptor) interceptor);
		}
	}
	int count = mappedInterceptors.size();
	return (count > 0 ? mappedInterceptors.toArray(new MappedInterceptor[count]) : null);
}
 
Example #24
Source File: ExtRequestMappingHandlerMapping.java    From onetwo with Apache License 2.0 5 votes vote down vote up
@Override
protected void detectMappedInterceptors(List<HandlerInterceptor> mappedInterceptors) {
	super.detectMappedInterceptors(mappedInterceptors);
	CUtils.stripNull(mappedInterceptors);
	Collections.sort(mappedInterceptors, new Comparator<HandlerInterceptor>() {

		@Override
		public int compare(HandlerInterceptor o1, HandlerInterceptor o2) {
			return OrderComparator.INSTANCE.compare(o1, o2);
		}
		
	});
}
 
Example #25
Source File: InterceptorRegistryTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void addWebRequestInterceptors() throws Exception {
	this.registry.addWebRequestInterceptor(this.webInterceptor1);
	this.registry.addWebRequestInterceptor(this.webInterceptor2);
	List<HandlerInterceptor> interceptors = getInterceptorsForPath(null);

	assertEquals(2, interceptors.size());
	verifyWebInterceptor(interceptors.get(0), this.webInterceptor1);
	verifyWebInterceptor(interceptors.get(1), this.webInterceptor2);
}
 
Example #26
Source File: InterceptorRegistryTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void addWebRequestInterceptors() throws Exception {
	this.registry.addWebRequestInterceptor(this.webInterceptor1);
	this.registry.addWebRequestInterceptor(this.webInterceptor2);
	List<HandlerInterceptor> interceptors = getInterceptorsForPath(null);

	assertEquals(2, interceptors.size());
	verifyWebInterceptor(interceptors.get(0), this.webInterceptor1);
	verifyWebInterceptor(interceptors.get(1), this.webInterceptor2);
}
 
Example #27
Source File: MappedInterceptor.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Create a new MappedInterceptor instance.
 * @param includePatterns the path patterns to map (empty for matching to all paths)
 * @param excludePatterns the path patterns to exclude (empty for no specific excludes)
 * @param interceptor the HandlerInterceptor instance to map to the given patterns
 */
public MappedInterceptor(@Nullable String[] includePatterns, @Nullable String[] excludePatterns,
		HandlerInterceptor interceptor) {

	this.includePatterns = includePatterns;
	this.excludePatterns = excludePatterns;
	this.interceptor = interceptor;
}
 
Example #28
Source File: HandlerMappingIntrospector.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
@Nullable
public CorsConfiguration getCorsConfiguration(HttpServletRequest request) {
	Assert.notNull(this.handlerMappings, "Handler mappings not initialized");
	HttpServletRequest wrapper = new RequestAttributeChangeIgnoringWrapper(request);
	for (HandlerMapping handlerMapping : this.handlerMappings) {
		HandlerExecutionChain handler = null;
		try {
			handler = handlerMapping.getHandler(wrapper);
		}
		catch (Exception ex) {
			// Ignore
		}
		if (handler == null) {
			continue;
		}
		if (handler.getInterceptors() != null) {
			for (HandlerInterceptor interceptor : handler.getInterceptors()) {
				if (interceptor instanceof CorsConfigurationSource) {
					return ((CorsConfigurationSource) interceptor).getCorsConfiguration(wrapper);
				}
			}
		}
		if (handler.getHandler() instanceof CorsConfigurationSource) {
			return ((CorsConfigurationSource) handler.getHandler()).getCorsConfiguration(wrapper);
		}
	}
	return null;
}
 
Example #29
Source File: HandlerMappingIntrospector.java    From foremast with Apache License 2.0 5 votes vote down vote up
@Override
public CorsConfiguration getCorsConfiguration(HttpServletRequest request) {
    Assert.notNull(this.handlerMappings, "Handler mappings not initialized");
    HttpServletRequest wrapper = new RequestAttributeChangeIgnoringWrapper(request);
    for (HandlerMapping handlerMapping : this.handlerMappings) {
        HandlerExecutionChain handler = null;
        try {
            handler = handlerMapping.getHandler(wrapper);
        }
        catch (Exception ex) {
            // Ignore
        }
        if (handler == null) {
            continue;
        }
        if (handler.getInterceptors() != null) {
            for (HandlerInterceptor interceptor : handler.getInterceptors()) {
                if (interceptor instanceof CorsConfigurationSource) {
                    return ((CorsConfigurationSource) interceptor).getCorsConfiguration(wrapper);
                }
            }
        }
        if (handler.getHandler() instanceof CorsConfigurationSource) {
            return ((CorsConfigurationSource) handler.getHandler()).getCorsConfiguration(wrapper);
        }
    }
    return null;
}
 
Example #30
Source File: StubMvcResult.java    From spring-analysis-note with MIT License 5 votes vote down vote up
public StubMvcResult(MockHttpServletRequest request,
					Object handler,
					HandlerInterceptor[] interceptors,
					Exception resolvedException,
					ModelAndView mav,
					FlashMap flashMap,
					MockHttpServletResponse response) {
	this.request = request;
	this.handler = handler;
	this.interceptors = interceptors;
	this.resolvedException = resolvedException;
	this.mav = mav;
	this.flashMap = flashMap;
	this.response = response;
}