001/* 002 * Copyright 2002-2019 the original author or authors. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * https://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package org.springframework.web.servlet.resource; 018 019import javax.servlet.http.HttpServletRequest; 020import javax.servlet.http.HttpServletResponse; 021 022import org.springframework.util.Assert; 023import org.springframework.web.bind.ServletRequestBindingException; 024import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; 025 026/** 027 * An interceptor that exposes the {@link ResourceUrlProvider} instance it 028 * is configured with as a request attribute. 029 * 030 * @author Rossen Stoyanchev 031 * @since 4.1 032 */ 033public class ResourceUrlProviderExposingInterceptor extends HandlerInterceptorAdapter { 034 035 /** 036 * Name of the request attribute that holds the {@link ResourceUrlProvider}. 037 */ 038 public static final String RESOURCE_URL_PROVIDER_ATTR = ResourceUrlProvider.class.getName(); 039 040 private final ResourceUrlProvider resourceUrlProvider; 041 042 043 public ResourceUrlProviderExposingInterceptor(ResourceUrlProvider resourceUrlProvider) { 044 Assert.notNull(resourceUrlProvider, "ResourceUrlProvider is required"); 045 this.resourceUrlProvider = resourceUrlProvider; 046 } 047 048 @Override 049 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) 050 throws Exception { 051 052 try { 053 request.setAttribute(RESOURCE_URL_PROVIDER_ATTR, this.resourceUrlProvider); 054 } 055 catch (ResourceUrlEncodingFilter.LookupPathIndexException ex) { 056 throw new ServletRequestBindingException(ex.getMessage(), ex); 057 } 058 return true; 059 } 060 061}