下面列出了org.springframework.context.i18n.TimeZoneAwareLocaleContext#org.springframework.web.util.UrlPathHelper 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Adds an alias to an existing well-known name or registers a new instance of a {@link UrlPathHelper}
* under that well-known name, unless already registered.
* @return a RuntimeBeanReference to this {@link UrlPathHelper} instance
*/
public static RuntimeBeanReference registerUrlPathHelper(RuntimeBeanReference urlPathHelperRef, ParserContext parserContext, Object source) {
if (urlPathHelperRef != null) {
if (parserContext.getRegistry().isAlias(URL_PATH_HELPER_BEAN_NAME)) {
parserContext.getRegistry().removeAlias(URL_PATH_HELPER_BEAN_NAME);
}
parserContext.getRegistry().registerAlias(urlPathHelperRef.getBeanName(), URL_PATH_HELPER_BEAN_NAME);
}
else if (!parserContext.getRegistry().isAlias(URL_PATH_HELPER_BEAN_NAME)
&& !parserContext.getRegistry().containsBeanDefinition(URL_PATH_HELPER_BEAN_NAME)) {
RootBeanDefinition urlPathHelperDef = new RootBeanDefinition(UrlPathHelper.class);
urlPathHelperDef.setSource(source);
urlPathHelperDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
parserContext.getRegistry().registerBeanDefinition(URL_PATH_HELPER_BEAN_NAME, urlPathHelperDef);
parserContext.registerComponent(new BeanComponentDefinition(urlPathHelperDef, URL_PATH_HELPER_BEAN_NAME));
}
return new RuntimeBeanReference(URL_PATH_HELPER_BEAN_NAME);
}
ForwardedHeaderExtractingRequest(HttpServletRequest request, UrlPathHelper pathHelper) {
super(request);
HttpRequest httpRequest = new ServletServerHttpRequest(request);
UriComponents uriComponents = UriComponentsBuilder.fromHttpRequest(httpRequest).build();
int port = uriComponents.getPort();
this.scheme = uriComponents.getScheme();
this.secure = "https".equals(this.scheme);
this.host = uriComponents.getHost();
this.port = (port == -1 ? (this.secure ? 443 : 80) : port);
String baseUrl = this.scheme + "://" + this.host + (port == -1 ? "" : ":" + port);
Supplier<HttpServletRequest> delegateRequest = () -> (HttpServletRequest) getRequest();
this.forwardedPrefixExtractor = new ForwardedPrefixExtractor(delegateRequest, pathHelper, baseUrl);
}
@Test
public void relativePathEncodedForUrlResource() throws Exception {
TestUrlResource location = new TestUrlResource("file:///tmp");
List<TestUrlResource> locations = Collections.singletonList(location);
// ISO-8859-1
this.resolver.setUrlPathHelper(new UrlPathHelper());
this.resolver.setLocationCharsets(Collections.singletonMap(location, StandardCharsets.ISO_8859_1));
this.resolver.resolveResource(new MockHttpServletRequest(), "/Ä ;ä.txt", locations, null);
assertEquals("%C4%20%3B%E4.txt", location.getSavedRelativePath());
// UTF-8
this.resolver.setLocationCharsets(Collections.singletonMap(location, StandardCharsets.UTF_8));
this.resolver.resolveResource(new MockHttpServletRequest(), "/Ä ;ä.txt", locations, null);
assertEquals("%C3%84%20%3B%C3%A4.txt", location.getSavedRelativePath());
// UTF-8 by default
this.resolver.setLocationCharsets(Collections.emptyMap());
this.resolver.resolveResource(new MockHttpServletRequest(), "/Ä ;ä.txt", locations, null);
assertEquals("%C3%84%20%3B%C3%A4.txt", location.getSavedRelativePath());
}
@SuppressWarnings("unchecked")
@Test // SPR-9098
public void handleMatchUriTemplateVariablesDecode() {
RequestMappingInfo key = RequestMappingInfo.paths("/{group}/{identifier}").build();
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/group/a%2Fb");
UrlPathHelper pathHelper = new UrlPathHelper();
pathHelper.setUrlDecode(false);
String lookupPath = pathHelper.getLookupPathForRequest(request);
this.handlerMapping.setUrlPathHelper(pathHelper);
this.handlerMapping.handleMatch(key, lookupPath, request);
String name = HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE;
Map<String, String> uriVariables = (Map<String, String>) request.getAttribute(name);
assertNotNull(uriVariables);
assertEquals("group", uriVariables.get("group"));
assertEquals("a/b", uriVariables.get("identifier"));
}
@Override
public int compareTo(StoreCondition other, HttpServletRequest request) {
if (this.isMappingForRequest(request)
&& other.isMappingForRequest(request) == false)
return 1;
else if (this.isMappingForRequest(request) == false
&& other.isMappingForRequest(request))
return -1;
else {
String path = new UrlPathHelper().getPathWithinApplication(request);
String storeLookupPath = ContentStoreUtils.storeLookupPath(path, baseUri);
String filename = FilenameUtils.getName(storeLookupPath);
String extension = FilenameUtils.getExtension(filename);
if (extension != null && "store".equals(storeType)) {
return -1;
}
else if (extension != null && "contentstore".equals(storeType)) {
return 1;
}
return 0;
}
}
public boolean isMappingForRequest(HttpServletRequest request) {
String path = new UrlPathHelper().getPathWithinApplication(request);
String storeLookupPath = ContentStoreUtils.storeLookupPath(path, baseUri);
String[] segments = storeLookupPath.split("/");
if (segments.length < 3) {
return false;
}
ContentStoreInfo info = ContentStoreUtils.findStore(stores, segments[1]);
if (info != null
&& (Store.class.isAssignableFrom(info.getInterface())
&& "store".equals(storeType))
|| (ContentStore.class.isAssignableFrom(info.getInterface())
&& "contentstore".equals(storeType))) {
return true;
}
return false;
}
private void initLookupPath(ResourceUrlProvider urlProvider) {
if (this.indexLookupPath == null) {
UrlPathHelper pathHelper = urlProvider.getUrlPathHelper();
String requestUri = pathHelper.getRequestUri(this.request);
String lookupPath = pathHelper.getLookupPathForRequest(this.request);
this.indexLookupPath = requestUri.lastIndexOf(lookupPath);
this.prefixLookupPath = requestUri.substring(0, this.indexLookupPath);
if ("/".equals(lookupPath) && !"/".equals(requestUri)) {
String contextPath = pathHelper.getContextPath(this.request);
if (requestUri.equals(contextPath)) {
this.indexLookupPath = requestUri.length();
this.prefixLookupPath = requestUri;
}
}
}
}
@SuppressWarnings("unchecked")
@Test // SPR-9098
public void handleMatchUriTemplateVariablesDecode() {
RequestMappingInfo key = RequestMappingInfo.paths("/{group}/{identifier}").build();
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/group/a%2Fb");
UrlPathHelper pathHelper = new UrlPathHelper();
pathHelper.setUrlDecode(false);
String lookupPath = pathHelper.getLookupPathForRequest(request);
this.handlerMapping.setUrlPathHelper(pathHelper);
this.handlerMapping.handleMatch(key, lookupPath, request);
String name = HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE;
Map<String, String> uriVariables = (Map<String, String>) request.getAttribute(name);
assertNotNull(uriVariables);
assertEquals("group", uriVariables.get("group"));
assertEquals("a/b", uriVariables.get("identifier"));
}
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
UrlPathHelper urlPathHelper = new UrlPathHelper();
urlPathHelper.setAlwaysUseFullPath(true);
configurer.setUrlPathHelper(urlPathHelper);
configurer.setUseSuffixPatternMatch(true);
}
@Before
public void setUp() {
GenericWebApplicationContext appContext = new GenericWebApplicationContext();
appContext.refresh();
this.registry = new ResourceHandlerRegistry(appContext, new MockServletContext(),
new ContentNegotiationManager(), new UrlPathHelper());
this.registration = this.registry.addResourceHandler("/resources/**");
this.registration.addResourceLocations("classpath:org/springframework/web/servlet/config/annotation/");
this.response = new MockHttpServletResponse();
}
@BeforeEach
public void setUp() {
MockitoAnnotations.initMocks(this);
when(httpServletRequest.getContextPath()).thenReturn("/servicea/test");
when(httpServletRequest.getRequestURI()).thenReturn("/servicea/test");
RequestContext requestContext = new RequestContext();
requestContext.setRequest(httpServletRequest);
RequestContext.testSetCurrentContext(requestContext);
RequestContextHolder.setRequestAttributes(requestAttributes);
rateLimitProperties = new RateLimitProperties();
UrlPathHelper urlPathHelper = new UrlPathHelper();
RateLimitUtils rateLimitUtils = new DefaultRateLimitUtils(rateLimitProperties);
target = new RateLimitPostFilter(rateLimitProperties, routeLocator, urlPathHelper, rateLimiter, rateLimitKeyGenerator, rateLimitUtils);
}
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
UrlPathHelper urlPathHelper = new UrlPathHelper();
urlPathHelper.setUrlDecode(false);
configurer.setUrlPathHelper(urlPathHelper);
configurer.setUseSuffixPatternMatch(false); // avoids bug with getInstanceFiles when instance name ends with .digit and it gets mangled
}
public CmsLog operating(HttpServletRequest request, String title,
String content) {
CmsSite site = CmsUtils.getSite(request);
CmsUser user = CmsUtils.getUser(request);
String ip = RequestUtils.getIpAddr(request);
UrlPathHelper helper = new UrlPathHelper();
String uri = helper.getOriginatingRequestUri(request);
Date date = new Date();
CmsLog log = save(CmsLog.OPERATING, site, user, uri, ip, date,
MessageResolver.getMessage(request, title), content);
return log;
}
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
final UrlPathHelper urlPathHelper = new UrlPathHelper();
urlPathHelper.setRemoveSemicolonContent(false);
configurer.setUrlPathHelper(urlPathHelper);
}
/**
* A variant of
* {@link #ResourceHandlerRegistry(ApplicationContext, ServletContext, ContentNegotiationManager)}
* that also accepts the {@link UrlPathHelper} used for mapping requests to static resources.
* @since 4.3.13
*/
public ResourceHandlerRegistry(ApplicationContext applicationContext, ServletContext servletContext,
@Nullable ContentNegotiationManager contentNegotiationManager, @Nullable UrlPathHelper pathHelper) {
Assert.notNull(applicationContext, "ApplicationContext is required");
this.applicationContext = applicationContext;
this.servletContext = servletContext;
this.contentNegotiationManager = contentNegotiationManager;
this.pathHelper = pathHelper;
}
AbstractRateLimitFilter(final RateLimitProperties properties, final RouteLocator routeLocator,
final UrlPathHelper urlPathHelper, final RateLimitUtils rateLimitUtils) {
this.properties = properties;
this.routeLocator = routeLocator;
this.urlPathHelper = urlPathHelper;
this.rateLimitUtils = rateLimitUtils;
}
@Test
public void configurePathMatch() throws Exception {
final PathMatcher pathMatcher = mock(PathMatcher.class);
final UrlPathHelper pathHelper = mock(UrlPathHelper.class);
List<WebMvcConfigurer> configurers = new ArrayList<>();
configurers.add(new WebMvcConfigurer() {
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
configurer.setUseRegisteredSuffixPatternMatch(true)
.setUseTrailingSlashMatch(false)
.setUrlPathHelper(pathHelper)
.setPathMatcher(pathMatcher);
}
});
delegatingConfig.setConfigurers(configurers);
RequestMappingHandlerMapping handlerMapping = delegatingConfig.requestMappingHandlerMapping(
delegatingConfig.mvcContentNegotiationManager(), delegatingConfig.mvcConversionService(),
delegatingConfig.mvcResourceUrlProvider());
assertNotNull(handlerMapping);
assertEquals("PathMatchConfigurer should configure RegisteredSuffixPatternMatch",
true, handlerMapping.useRegisteredSuffixPatternMatch());
assertEquals("PathMatchConfigurer should configure SuffixPatternMatch",
true, handlerMapping.useSuffixPatternMatch());
assertEquals("PathMatchConfigurer should configure TrailingSlashMatch",
false, handlerMapping.useTrailingSlashMatch());
assertEquals("PathMatchConfigurer should configure UrlPathHelper",
pathHelper, handlerMapping.getUrlPathHelper());
assertEquals("PathMatchConfigurer should configure PathMatcher",
pathMatcher, handlerMapping.getPathMatcher());
}
@Override
public boolean execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
UrlPathHelper urlPathHelper = new UrlPathHelper();
String originalPath = urlPathHelper.getLookupPathForRequest(request);
String rewritePath = originalPath.replaceAll("^/" + blogLanguage.getLanguage() + "/", "/");
matchingUrl = rewritePath;
logger.debug(originalPath + " => " + rewritePath);
request.setAttribute(BlogLanguageMethodArgumentResolver.BLOG_LANGUAGE_ATTRIBUTE, blogLanguage);
RequestDispatcher rd = request.getRequestDispatcher(urlPathHelper.getServletPath(request) + rewritePath);
rd.forward(request, response);
return true;
}
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
UrlPathHelper urlPathHelper = new UrlPathHelper();
urlPathHelper.setAlwaysUseFullPath(true);
configurer.setUrlPathHelper(urlPathHelper);
configurer.setUseSuffixPatternMatch(true);
}
@Override
public void configurePathMatch(final PathMatchConfigurer configurer) {
final UrlPathHelper urlPathHelper = new UrlPathHelper();
urlPathHelper.setRemoveSemicolonContent(false);
configurer.setUrlPathHelper(urlPathHelper);
}
@Test
public void configurePathMatch() throws Exception {
final PathMatcher pathMatcher = mock(PathMatcher.class);
final UrlPathHelper pathHelper = mock(UrlPathHelper.class);
List<WebMvcConfigurer> configurers = new ArrayList<>();
configurers.add(new WebMvcConfigurer() {
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
configurer.setUseRegisteredSuffixPatternMatch(true)
.setUseTrailingSlashMatch(false)
.setUrlPathHelper(pathHelper)
.setPathMatcher(pathMatcher);
}
});
delegatingConfig.setConfigurers(configurers);
RequestMappingHandlerMapping handlerMapping = delegatingConfig.requestMappingHandlerMapping();
assertNotNull(handlerMapping);
assertEquals("PathMatchConfigurer should configure RegisteredSuffixPatternMatch",
true, handlerMapping.useRegisteredSuffixPatternMatch());
assertEquals("PathMatchConfigurer should configure SuffixPatternMatch",
true, handlerMapping.useSuffixPatternMatch());
assertEquals("PathMatchConfigurer should configure TrailingSlashMatch",
false, handlerMapping.useTrailingSlashMatch());
assertEquals("PathMatchConfigurer should configure UrlPathHelper",
pathHelper, handlerMapping.getUrlPathHelper());
assertEquals("PathMatchConfigurer should configure PathMatcher",
pathMatcher, handlerMapping.getPathMatcher());
}
/**
* A variant of
* {@link #ResourceHandlerRegistry(ApplicationContext, ServletContext, ContentNegotiationManager)}
* that also accepts the {@link UrlPathHelper} used for mapping requests to static resources.
* @since 4.3.13
*/
public ResourceHandlerRegistry(ApplicationContext applicationContext, ServletContext servletContext,
@Nullable ContentNegotiationManager contentNegotiationManager, @Nullable UrlPathHelper pathHelper) {
Assert.notNull(applicationContext, "ApplicationContext is required");
this.applicationContext = applicationContext;
this.servletContext = servletContext;
this.contentNegotiationManager = contentNegotiationManager;
this.pathHelper = pathHelper;
}
/**
* Configures the PathMatchConfigurer with UrlPathHelper
* @param configurer PathMatchConfigurer
*/
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
UrlPathHelper urlPathHelper = new UrlPathHelper();
urlPathHelper.setUrlDecode(false);
configurer.setUrlPathHelper(urlPathHelper);
}
@Test
public void configurePathMatch() throws Exception {
final PathMatcher pathMatcher = mock(PathMatcher.class);
final UrlPathHelper pathHelper = mock(UrlPathHelper.class);
List<WebMvcConfigurer> configurers = new ArrayList<WebMvcConfigurer>();
configurers.add(new WebMvcConfigurerAdapter() {
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
configurer.setUseRegisteredSuffixPatternMatch(true)
.setUseTrailingSlashMatch(false)
.setUrlPathHelper(pathHelper)
.setPathMatcher(pathMatcher);
}
});
delegatingConfig.setConfigurers(configurers);
RequestMappingHandlerMapping handlerMapping = delegatingConfig.requestMappingHandlerMapping();
assertNotNull(handlerMapping);
assertEquals("PathMatchConfigurer should configure RegisteredSuffixPatternMatch",
true, handlerMapping.useRegisteredSuffixPatternMatch());
assertEquals("PathMatchConfigurer should configure SuffixPatternMatch",
true, handlerMapping.useSuffixPatternMatch());
assertEquals("PathMatchConfigurer should configure TrailingSlashMatch",
false, handlerMapping.useTrailingSlashMatch());
assertEquals("PathMatchConfigurer should configure UrlPathHelper",
pathHelper, handlerMapping.getUrlPathHelper());
assertEquals("PathMatchConfigurer should configure PathMatcher",
pathMatcher, handlerMapping.getPathMatcher());
}
/**
* Configures the PathMatchConfigurer with UrlPathHelper
* @param configurer PathMatchConfigurer
*/
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
UrlPathHelper urlPathHelper = new UrlPathHelper();
urlPathHelper.setUrlDecode(false);
configurer.setUrlPathHelper(urlPathHelper);
}
/**
* Set the UrlPathHelper to use for resolution of lookup paths.
* <p>Use this to override the default UrlPathHelper with a custom subclass,
* or to share common UrlPathHelper settings across multiple HandlerMappings
* and MethodNameResolvers.
*/
public void setUrlPathHelper(UrlPathHelper urlPathHelper) {
Assert.notNull(urlPathHelper, "UrlPathHelper must not be null");
this.urlPathHelper = urlPathHelper;
if (this.corsConfigurationSource instanceof UrlBasedCorsConfigurationSource) {
((UrlBasedCorsConfigurationSource)this.corsConfigurationSource).setUrlPathHelper(urlPathHelper);
}
}
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
UrlPathHelper urlPathHelper = new UrlPathHelper();
urlPathHelper.setAlwaysUseFullPath(true);
configurer.setUrlPathHelper(urlPathHelper);
configurer.setUseSuffixPatternMatch(true);
}
/**
* Create a new RequestContext for the given request, using the given model attributes for Errors retrieval.
* <p>This works with all View implementations. It will typically be used by View implementations.
* <p>If a ServletContext is specified, the RequestContext will also work with a root
* WebApplicationContext (outside a DispatcherServlet).
* @param request current HTTP request
* @param response current HTTP response
* @param servletContext the servlet context of the web application (can be {@code null}; necessary for
* fallback to root WebApplicationContext)
* @param model the model attributes for the current view (can be {@code null}, using the request attributes
* for Errors retrieval)
* @see org.springframework.web.context.WebApplicationContext
* @see org.springframework.web.servlet.DispatcherServlet
*/
public RequestContext(HttpServletRequest request, @Nullable HttpServletResponse response,
@Nullable ServletContext servletContext, @Nullable Map<String, Object> model) {
this.request = request;
this.response = response;
this.model = model;
// Fetch WebApplicationContext, either from DispatcherServlet or the root context.
// ServletContext needs to be specified to be able to fall back to the root context!
WebApplicationContext wac = (WebApplicationContext) request.getAttribute(WEB_APPLICATION_CONTEXT_ATTRIBUTE);
if (wac == null) {
wac = RequestContextUtils.findWebApplicationContext(request, servletContext);
if (wac == null) {
throw new IllegalStateException("No WebApplicationContext found: not in a DispatcherServlet " +
"request and no ContextLoaderListener registered?");
}
}
this.webApplicationContext = wac;
Locale locale = null;
TimeZone timeZone = null;
// Determine locale to use for this RequestContext.
LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request);
if (localeResolver instanceof LocaleContextResolver) {
LocaleContext localeContext = ((LocaleContextResolver) localeResolver).resolveLocaleContext(request);
locale = localeContext.getLocale();
if (localeContext instanceof TimeZoneAwareLocaleContext) {
timeZone = ((TimeZoneAwareLocaleContext) localeContext).getTimeZone();
}
}
else if (localeResolver != null) {
// Try LocaleResolver (we're within a DispatcherServlet request).
locale = localeResolver.resolveLocale(request);
}
this.locale = locale;
this.timeZone = timeZone;
// Determine default HTML escape setting from the "defaultHtmlEscape"
// context-param in web.xml, if any.
this.defaultHtmlEscape = WebUtils.getDefaultHtmlEscape(this.webApplicationContext.getServletContext());
// Determine response-encoded HTML escape setting from the "responseEncodedHtmlEscape"
// context-param in web.xml, if any.
this.responseEncodedHtmlEscape =
WebUtils.getResponseEncodedHtmlEscape(this.webApplicationContext.getServletContext());
this.urlPathHelper = new UrlPathHelper();
if (this.webApplicationContext.containsBean(RequestContextUtils.REQUEST_DATA_VALUE_PROCESSOR_BEAN_NAME)) {
this.requestDataValueProcessor = this.webApplicationContext.getBean(
RequestContextUtils.REQUEST_DATA_VALUE_PROCESSOR_BEAN_NAME, RequestDataValueProcessor.class);
}
}
private int getLookupPathIndex(HttpServletRequest request) {
UrlPathHelper pathHelper = getUrlPathHelper();
String requestUri = pathHelper.getRequestUri(request);
String lookupPath = this.urlPathHelper.getLookupPathForRequest(request, HandlerMapping.LOOKUP_PATH);
return requestUri.indexOf(lookupPath);
}
/**
* Return the configured {@code UrlPathHelper}.
*/
public UrlPathHelper getPathHelper() {
return this.pathHelper;
}