org.springframework.web.servlet.HandlerMapping Java Examples
The following examples show how to use
org.springframework.web.servlet.HandlerMapping.
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: ExtendedServletRequestDataBinderTests.java From spring4-understanding with Apache License 2.0 | 6 votes |
@Test public void uriTemplateVarAndRequestParam() throws Exception { request.addParameter("age", "35"); Map<String, String> uriTemplateVars = new HashMap<String, String>(); uriTemplateVars.put("name", "nameValue"); uriTemplateVars.put("age", "25"); request.setAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, uriTemplateVars); TestBean target = new TestBean(); WebDataBinder binder = new ExtendedServletRequestDataBinder(target, ""); ((ServletRequestDataBinder) binder).bind(request); assertEquals("nameValue", target.getName()); assertEquals(35, target.getAge()); }
Example #2
Source File: APISecurityInterceptor.java From singleton with Eclipse Public License 2.0 | 6 votes |
/** * Get data and verify token * * @param request HttpServletRequest object * @return If true, authentication is passed, otherwise not */ @SuppressWarnings("unchecked") private boolean verifyRightForResouceAccess(HttpServletRequest request) { String token = request.getHeader(ConstantsKeys.TOKEN); if (StringUtils.isEmpty(token)) return false; String[] tArray = token.split(ConstantsKeys.VIP.hashCode() + ""); Map<String, String> pathVariables = (Map<String, String>) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE); String productName = pathVariables.get(ConstantsKeys.PRODUCTNAME) == null ? request.getParameter(ConstantsKeys.PRODUCTNAME) : pathVariables.get(ConstantsKeys.PRODUCTNAME); String version = pathVariables.get(ConstantsKeys.VERSION) == null ? request.getParameter(ConstantsKeys.VERSION) : pathVariables.get(ConstantsKeys.VERSION); if (!StringUtils.isEmpty(productName) && !StringUtils.isEmpty(version)) { String productName_version = tArray[0]; if (!productName_version.equals((productName + ConstantsChar.UNDERLINE + version).hashCode()+"")) return false; } if (token.indexOf(String.valueOf(ConstantsKeys.VIP.hashCode())) <= 0) return false; return true; }
Example #3
Source File: WebMvcConfigurationSupport.java From spring-analysis-note with MIT License | 6 votes |
/** * Return a handler mapping ordered at Integer.MAX_VALUE-1 with mapped * resource handlers. To configure resource handling, override * {@link #addResourceHandlers}. */ @Bean @Nullable public HandlerMapping resourceHandlerMapping(UrlPathHelper mvcUrlPathHelper, PathMatcher mvcPathMatcher, ContentNegotiationManager mvcContentNegotiationManager, FormattingConversionService mvcConversionService, ResourceUrlProvider mvcResourceUrlProvider) { Assert.state(this.applicationContext != null, "No ApplicationContext set"); Assert.state(this.servletContext != null, "No ServletContext set"); ResourceHandlerRegistry registry = new ResourceHandlerRegistry(this.applicationContext, this.servletContext, mvcContentNegotiationManager, mvcUrlPathHelper); addResourceHandlers(registry); AbstractHandlerMapping handlerMapping = registry.getHandlerMapping(); if (handlerMapping == null) { return null; } handlerMapping.setPathMatcher(mvcPathMatcher); handlerMapping.setUrlPathHelper(mvcUrlPathHelper); handlerMapping.setInterceptors(getInterceptors(mvcConversionService, mvcResourceUrlProvider)); handlerMapping.setCorsConfigurations(getCorsConfigurations()); return handlerMapping; }
Example #4
Source File: WebMvcConfigurationSupport.java From spring-analysis-note with MIT License | 6 votes |
/** * Return a handler mapping ordered at 1 to map URL paths directly to * view names. To configure view controllers, override * {@link #addViewControllers}. */ @Bean @Nullable public HandlerMapping viewControllerHandlerMapping(PathMatcher mvcPathMatcher, UrlPathHelper mvcUrlPathHelper, FormattingConversionService mvcConversionService, ResourceUrlProvider mvcResourceUrlProvider) { ViewControllerRegistry registry = new ViewControllerRegistry(this.applicationContext); addViewControllers(registry); AbstractHandlerMapping handlerMapping = registry.buildHandlerMapping(); if (handlerMapping == null) { return null; } handlerMapping.setPathMatcher(mvcPathMatcher); handlerMapping.setUrlPathHelper(mvcUrlPathHelper); handlerMapping.setInterceptors(getInterceptors(mvcConversionService, mvcResourceUrlProvider)); handlerMapping.setCorsConfigurations(getCorsConfigurations()); return handlerMapping; }
Example #5
Source File: CollectSourceValidationInterceptor.java From singleton with Eclipse Public License 2.0 | 6 votes |
@SuppressWarnings("unchecked") private static void validateLocale(HttpServletRequest request, List<String> sourceLocales2) throws VIPAPIException { Map<String, String> pathVariables = (Map<String, String>) request .getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE); String locale = pathVariables.get(APIParamName.LOCALE) == null ? request .getParameter(APIParamName.LOCALE) : pathVariables .get(APIParamName.LOCALE); if (StringUtils.isEmpty(locale)) { return; } if (!RegExpValidatorUtils.IsLetterAndNumberAndValidchar(locale)) { throw new VIPAPIException(ValidationMsg.LOCALE_NOT_VALIDE); }else if (!sourceLocales2.contains(locale)) { throw new VIPAPIException(ValidationMsg.LOCALE_NOT_VALIDE); } }
Example #6
Source File: ExtendedServletRequestDataBinderTests.java From java-technology-stack with MIT License | 6 votes |
@Test public void uriTemplateVarAndRequestParam() throws Exception { request.addParameter("age", "35"); Map<String, String> uriTemplateVars = new HashMap<>(); uriTemplateVars.put("name", "nameValue"); uriTemplateVars.put("age", "25"); request.setAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, uriTemplateVars); TestBean target = new TestBean(); WebDataBinder binder = new ExtendedServletRequestDataBinder(target, ""); ((ServletRequestDataBinder) binder).bind(request); assertEquals("nameValue", target.getName()); assertEquals(35, target.getAge()); }
Example #7
Source File: WebMvcConfigurationSupport.java From lams with GNU General Public License v2.0 | 6 votes |
/** * 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, mvcContentNegotiationManager()); addResourceHandlers(registry); AbstractHandlerMapping handlerMapping = registry.getHandlerMapping(); if (handlerMapping != null) { handlerMapping.setPathMatcher(mvcPathMatcher()); handlerMapping.setUrlPathHelper(mvcUrlPathHelper()); handlerMapping.setInterceptors(new ResourceUrlProviderExposingInterceptor(mvcResourceUrlProvider())); handlerMapping.setCorsConfigurations(getCorsConfigurations()); } else { handlerMapping = new EmptyHandlerMapping(); } return handlerMapping; }
Example #8
Source File: WebMvcConfigurationSupportTests.java From spring-analysis-note with MIT License | 6 votes |
@Test public void emptyHandlerMappings() { ApplicationContext context = initContext(WebConfig.class); Map<String, HandlerMapping> handlerMappings = context.getBeansOfType(HandlerMapping.class); assertFalse(handlerMappings.containsKey("viewControllerHandlerMapping")); assertFalse(handlerMappings.containsKey("resourceHandlerMapping")); assertFalse(handlerMappings.containsKey("defaultServletHandlerMapping")); Object nullBean = context.getBean("viewControllerHandlerMapping"); assertTrue(nullBean.equals(null)); nullBean = context.getBean("resourceHandlerMapping"); assertTrue(nullBean.equals(null)); nullBean = context.getBean("defaultServletHandlerMapping"); assertTrue(nullBean.equals(null)); }
Example #9
Source File: HandlerMappingIntrospector.java From foremast with Apache License 2.0 | 6 votes |
/** * Find the {@link HandlerMapping} that would handle the given request and * return it as a {@link MatchableHandlerMapping} that can be used to test * request-matching criteria. * <p>If the matching HandlerMapping is not an instance of * {@link MatchableHandlerMapping}, an IllegalStateException is raised. * @param request the current request * @return the resolved matcher, or {@code null} * @throws Exception if any of the HandlerMapping's raise an exception */ public HandlerExecutionChain getHandlerExecutionChain(HttpServletRequest request) throws Exception { Assert.notNull(this.handlerMappings, "Handler mappings not initialized"); HttpServletRequest wrapper = new RequestAttributeChangeIgnoringWrapper(request); for (HandlerMapping handlerMapping : this.handlerMappings) { Object handler = handlerMapping.getHandler(wrapper); if (handler == null) { continue; } if (handler instanceof HandlerExecutionChain) { return (HandlerExecutionChain)handler; } throw new IllegalStateException("HandlerMapping is not a MatchableHandlerMapping"); } return null; }
Example #10
Source File: PathVariableMethodArgumentResolverTests.java From spring-analysis-note with MIT License | 6 votes |
@Test public void resolveArgumentWrappedAsOptional() throws Exception { Map<String, String> uriTemplateVars = new HashMap<>(); uriTemplateVars.put("name", "value"); request.setAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, uriTemplateVars); ConfigurableWebBindingInitializer initializer = new ConfigurableWebBindingInitializer(); initializer.setConversionService(new DefaultConversionService()); WebDataBinderFactory binderFactory = new DefaultDataBinderFactory(initializer); @SuppressWarnings("unchecked") Optional<String> result = (Optional<String>) resolver.resolveArgument(paramOptional, mavContainer, webRequest, binderFactory); assertEquals("PathVariable not resolved correctly", "value", result.get()); @SuppressWarnings("unchecked") Map<String, Object> pathVars = (Map<String, Object>) request.getAttribute(View.PATH_VARIABLES); assertNotNull(pathVars); assertEquals(1, pathVars.size()); assertEquals(Optional.of("value"), pathVars.get("name")); }
Example #11
Source File: PathVariableMethodArgumentResolverTests.java From spring-analysis-note with MIT License | 6 votes |
@Test public void resolveArgumentWithExistingPathVars() throws Exception { Map<String, String> uriTemplateVars = new HashMap<>(); uriTemplateVars.put("name", "value"); request.setAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, uriTemplateVars); uriTemplateVars.put("oldName", "oldValue"); request.setAttribute(View.PATH_VARIABLES, uriTemplateVars); String result = (String) resolver.resolveArgument(paramNamedString, mavContainer, webRequest, null); assertEquals("PathVariable not resolved correctly", "value", result); @SuppressWarnings("unchecked") Map<String, Object> pathVars = (Map<String, Object>) request.getAttribute(View.PATH_VARIABLES); assertNotNull(pathVars); assertEquals(2, pathVars.size()); assertEquals("value", pathVars.get("name")); assertEquals("oldValue", pathVars.get("oldName")); }
Example #12
Source File: ResourceHttpRequestHandlerTests.java From java-technology-stack with MIT License | 5 votes |
@Test public void partialContentInvalidRangeHeader() throws Exception { this.request.addHeader("Range", "bytes= foo bar"); this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.txt"); this.handler.handleRequest(this.request, this.response); assertEquals(416, this.response.getStatus()); assertEquals("bytes */10", this.response.getHeader("Content-Range")); assertEquals("bytes", this.response.getHeader("Accept-Ranges")); assertEquals(1, this.response.getHeaders("Accept-Ranges").size()); }
Example #13
Source File: ReactiveTypeHandlerTests.java From spring-analysis-note with MIT License | 5 votes |
@Test public void mediaTypes() throws Exception { // Media type from request this.servletRequest.addHeader("Accept", "text/event-stream"); testSseResponse(true); // Media type from "produces" attribute Set<MediaType> types = Collections.singleton(MediaType.TEXT_EVENT_STREAM); this.servletRequest.setAttribute(HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE, types); testSseResponse(true); // No media type preferences testSseResponse(false); }
Example #14
Source File: ServletModelAttributeMethodProcessorTests.java From java-technology-stack with MIT License | 5 votes |
@Test public void createAttributeUriTemplateVar() throws Exception { Map<String, String> uriTemplateVars = new HashMap<>(); uriTemplateVars.put("testBean1", "Patty"); request.setAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, uriTemplateVars); // Type conversion from "Patty" to TestBean via TestBean(String) constructor TestBean testBean = (TestBean) processor.resolveArgument( testBeanModelAttr, mavContainer, webRequest, binderFactory); assertEquals("Patty", testBean.getName()); }
Example #15
Source File: ContentNegotiatingViewResolver.java From lams with GNU General Public License v2.0 | 5 votes |
@SuppressWarnings("unchecked") private List<MediaType> getProducibleMediaTypes(HttpServletRequest request) { Set<MediaType> mediaTypes = (Set<MediaType>) request.getAttribute(HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE); if (!CollectionUtils.isEmpty(mediaTypes)) { return new ArrayList<MediaType>(mediaTypes); } else { return Collections.singletonList(MediaType.ALL); } }
Example #16
Source File: ExtendedServletRequestDataBinderTests.java From spring-analysis-note with MIT License | 5 votes |
@Test public void createBinder() throws Exception { Map<String, String> uriTemplateVars = new HashMap<>(); uriTemplateVars.put("name", "nameValue"); uriTemplateVars.put("age", "25"); request.setAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, uriTemplateVars); TestBean target = new TestBean(); WebDataBinder binder = new ExtendedServletRequestDataBinder(target, ""); ((ServletRequestDataBinder) binder).bind(request); assertEquals("nameValue", target.getName()); assertEquals(25, target.getAge()); }
Example #17
Source File: WebSocketMessageBrokerConfigurationSupportTests.java From spring-analysis-note with MIT License | 5 votes |
@Test public void handlerMapping() { ApplicationContext config = createConfig(TestChannelConfig.class, TestConfigurer.class); SimpleUrlHandlerMapping hm = (SimpleUrlHandlerMapping) config.getBean(HandlerMapping.class); assertEquals(1, hm.getOrder()); Map<String, Object> handlerMap = hm.getHandlerMap(); assertEquals(1, handlerMap.size()); assertNotNull(handlerMap.get("/simpleBroker")); }
Example #18
Source File: RequestAttributeAssertionTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Test public void testRequestAttributeMatcher() throws Exception { String producibleMediaTypes = HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE; this.mockMvc.perform(get("/1")) .andExpect(request().attribute(producibleMediaTypes, hasItem(MediaType.APPLICATION_JSON))) .andExpect(request().attribute(producibleMediaTypes, not(hasItem(MediaType.APPLICATION_XML)))); }
Example #19
Source File: MatrixVariablesMethodArgumentResolverTests.java From spring-analysis-note with MIT License | 5 votes |
@SuppressWarnings("unchecked") private MultiValueMap<String, String> getVariablesFor(String pathVarName) { Map<String, MultiValueMap<String, String>> matrixVariables = (Map<String, MultiValueMap<String, String>>) this.request.getAttribute( HandlerMapping.MATRIX_VARIABLES_ATTRIBUTE); MultiValueMap<String, String> params = new LinkedMultiValueMap<>(); matrixVariables.put(pathVarName, params); return params; }
Example #20
Source File: SimpleUrlHandlerMappingTests.java From spring-analysis-note with MIT License | 5 votes |
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 #21
Source File: HandlerMappingIntrospector.java From lams with GNU General Public License v2.0 | 5 votes |
@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: ResourceHttpRequestHandlerTests.java From spring-analysis-note with MIT License | 5 votes |
private void testResolvePathWithTraversal(Resource location, String requestPath) throws Exception { this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, requestPath); this.response = new MockHttpServletResponse(); this.handler.handleRequest(this.request, this.response); if (!location.createRelative(requestPath).exists() && !requestPath.contains(":")) { fail(requestPath + " doesn't actually exist as a relative path"); } assertEquals(HttpStatus.NOT_FOUND.value(), this.response.getStatus()); }
Example #23
Source File: ParameterValidation.java From singleton with Eclipse Public License 2.0 | 5 votes |
@SuppressWarnings("unchecked") private void validateComponent(HttpServletRequest request) throws ValidationException { Map<String, String> pathVariables = (Map<String, String>) request .getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE); String component = pathVariables.get(APIParamName.COMPONENT) == null ? request .getParameter(APIParamName.COMPONENT) : pathVariables .get(APIParamName.COMPONENT); if (StringUtils.isEmpty(component)) { return; } if (!RegExpValidatorUtils.IsLetterAndNumberAndValidchar(component)) { throw new ValidationException(ValidationMsg.COMPONENT_NOT_VALIDE); } }
Example #24
Source File: HandlerMethodMappingTests.java From java-technology-stack with MIT License | 5 votes |
@Test public void directMatch() throws Exception { String key = "foo"; this.mapping.registerMapping(key, this.handler, this.method1); MockHttpServletRequest request = new MockHttpServletRequest("GET", key); HandlerMethod result = this.mapping.getHandlerInternal(request); assertEquals(method1, result.getMethod()); assertEquals(result, request.getAttribute(HandlerMapping.BEST_MATCHING_HANDLER_ATTRIBUTE)); }
Example #25
Source File: HandlerMappingIntrospectorTests.java From spring-analysis-note with MIT License | 5 votes |
public void defaultHandlerMappings() throws Exception { StaticWebApplicationContext cxt = new StaticWebApplicationContext(); cxt.refresh(); List<HandlerMapping> actual = getIntrospector(cxt).getHandlerMappings(); assertEquals(2, actual.size()); assertEquals(BeanNameUrlHandlerMapping.class, actual.get(0).getClass()); assertEquals(RequestMappingHandlerMapping.class, actual.get(1).getClass()); }
Example #26
Source File: ResourceHttpRequestHandlerTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Test public void getResourceFromSubDirectory() throws Exception { this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "js/foo.js"); this.handler.handleRequest(this.request, this.response); assertEquals("text/javascript", this.response.getContentType()); assertEquals("function foo() { console.log(\"hello world\"); }", this.response.getContentAsString()); }
Example #27
Source File: ResourceHttpRequestHandlerTests.java From spring-analysis-note with MIT License | 5 votes |
@Test public void getResourceFromSubDirectoryOfAlternatePath() throws Exception { this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "js/baz.js"); this.handler.handleRequest(this.request, this.response); assertEquals("text/javascript", this.response.getContentType()); assertEquals("function foo() { console.log(\"hello world\"); }", this.response.getContentAsString()); }
Example #28
Source File: ResourceHttpRequestHandlerTests.java From spring-analysis-note with MIT License | 5 votes |
@Test public void getResourceFromAlternatePath() throws Exception { this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "baz.css"); this.handler.handleRequest(this.request, this.response); assertEquals("text/css", this.response.getContentType()); assertEquals(17, this.response.getContentLength()); assertEquals("max-age=3600", this.response.getHeader("Cache-Control")); assertTrue(this.response.containsHeader("Last-Modified")); assertEquals(resourceLastModified("testalternatepath/baz.css") / 1000, this.response.getDateHeader("Last-Modified") / 1000); assertEquals("bytes", this.response.getHeader("Accept-Ranges")); assertEquals(1, this.response.getHeaders("Accept-Ranges").size()); assertEquals("h1 { color:red; }", this.response.getContentAsString()); }
Example #29
Source File: ResourceHttpRequestHandlerTests.java From java-technology-stack with MIT License | 5 votes |
@Test // SPR-14005 public void doOverwriteExistingCacheControlHeaders() throws Exception { this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.css"); this.response.setHeader("Cache-Control", "no-store"); this.handler.handleRequest(this.request, this.response); assertEquals("max-age=3600", this.response.getHeader("Cache-Control")); }
Example #30
Source File: ServletModelAttributeMethodProcessorTests.java From spring-analysis-note with MIT License | 5 votes |
@Test public void createAttributeUriTemplateVarCannotConvert() throws Exception { Map<String, String> uriTemplateVars = new HashMap<>(); uriTemplateVars.put("testBean2", "Patty"); request.setAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, uriTemplateVars); TestBeanWithoutStringConstructor testBean = (TestBeanWithoutStringConstructor) processor.resolveArgument( testBeanWithoutStringConstructorModelAttr, mavContainer, webRequest, binderFactory); assertNotNull(testBean); }