下面列出了org.springframework.web.servlet.handler.HandlerInterceptorAdapter#org.springframework.web.servlet.HandlerInterceptor 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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);
}
@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;
}
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;
}
@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]);
}
/**
* 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());
}
}
}
/**
* 拦截器,只有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;
}
};
}
/**
* 动态删除拦截器
* @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);
}
}
/**
* 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;
}
@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());
}
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;
}
/**
* 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());
}
}
}
@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]);
}
@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);
}
@Test
public void addWebRequestInterceptor() throws Exception {
this.registry.addWebRequestInterceptor(this.webInterceptor1);
List<HandlerInterceptor> interceptors = getInterceptorsForPath(null);
assertEquals(1, interceptors.size());
verifyWebInterceptor(interceptors.get(0), this.webInterceptor1);
}
@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());
}
@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;
}
/**
* 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);
}
/**
* 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;
}
@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());
}
@Test
public void postHandle() throws Exception {
HandlerInterceptor interceptor = mock(HandlerInterceptor.class);
MappedInterceptor mappedInterceptor = new MappedInterceptor(new String[] { "/**" }, interceptor);
mappedInterceptor.postHandle(mock(HttpServletRequest.class), mock(HttpServletResponse.class),
null, mock(ModelAndView.class));
then(interceptor).should().postHandle(any(), any(), any(), any());
}
@Test
public void testResources() throws Exception {
loadBeanDefinitions("mvc-config-resources.xml", 10);
HttpRequestHandlerAdapter adapter = appContext.getBean(HttpRequestHandlerAdapter.class);
assertNotNull(adapter);
ResourceHttpRequestHandler handler = appContext.getBean(ResourceHttpRequestHandler.class);
assertNotNull(handler);
SimpleUrlHandlerMapping mapping = appContext.getBean(SimpleUrlHandlerMapping.class);
assertNotNull(mapping);
assertEquals(Ordered.LOWEST_PRECEDENCE - 1, mapping.getOrder());
BeanNameUrlHandlerMapping beanNameMapping = appContext.getBean(BeanNameUrlHandlerMapping.class);
assertNotNull(beanNameMapping);
assertEquals(2, beanNameMapping.getOrder());
ResourceUrlProvider urlProvider = appContext.getBean(ResourceUrlProvider.class);
assertNotNull(urlProvider);
MappedInterceptor mappedInterceptor = appContext.getBean(MappedInterceptor.class);
assertNotNull(urlProvider);
assertEquals(ResourceUrlProviderExposingInterceptor.class, mappedInterceptor.getInterceptor().getClass());
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRequestURI("/resources/foo.css");
request.setMethod("GET");
HandlerExecutionChain chain = mapping.getHandler(request);
assertTrue(chain.getHandler() instanceof ResourceHttpRequestHandler);
MockHttpServletResponse response = new MockHttpServletResponse();
for (HandlerInterceptor interceptor : chain.getInterceptors()) {
interceptor.preHandle(request, response, chain.getHandler());
}
ModelAndView mv = adapter.handle(request, response, chain.getHandler());
assertNull(mv);
}
@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);
}
private HandlerExecutionChain getHandler(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;
}
@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);
}
/**
* 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;
}
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;
}
/**
* 在控制器(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);
}
@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;
}
@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;
}
/**
* 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;
}