org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping Java Examples

The following examples show how to use org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping. 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: SbpMvcPatchAutoConfiguration.java    From sbp with Apache License 2.0 6 votes vote down vote up
@Bean
@ConditionalOnMissingBean(WebMvcRegistrations.class)
public WebMvcRegistrations mvcRegistrations() {
	return new WebMvcRegistrations() {
		@Override
		public RequestMappingHandlerMapping getRequestMappingHandlerMapping() {
			return new PluginRequestMappingHandlerMapping();
		}

		@Override
		public RequestMappingHandlerAdapter getRequestMappingHandlerAdapter() {
			return null;
		}

		@Override
		public ExceptionHandlerExceptionResolver getExceptionHandlerExceptionResolver() {
			return null;
		}
	};
}
 
Example #2
Source File: MvcNamespaceTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test(expected = TypeMismatchException.class)
public void testCustomConversionService() throws Exception {
	loadBeanDefinitions("mvc-config-custom-conversion-service.xml", 14);

	RequestMappingHandlerMapping mapping = appContext.getBean(RequestMappingHandlerMapping.class);
	assertNotNull(mapping);
	mapping.setDefaultHandler(handlerMethod);

	// default web binding initializer behavior test
	MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
	request.setRequestURI("/accounts/12345");
	request.addParameter("date", "2009-10-31");
	MockHttpServletResponse response = new MockHttpServletResponse();

	HandlerExecutionChain chain = mapping.getHandler(request);
	assertEquals(1, chain.getInterceptors().length);
	assertTrue(chain.getInterceptors()[0] instanceof ConversionServiceExposingInterceptor);
	ConversionServiceExposingInterceptor interceptor = (ConversionServiceExposingInterceptor) chain.getInterceptors()[0];
	interceptor.preHandle(request, response, handler);
	assertSame(appContext.getBean("conversionService"), request.getAttribute(ConversionService.class.getName()));

	RequestMappingHandlerAdapter adapter = appContext.getBean(RequestMappingHandlerAdapter.class);
	assertNotNull(adapter);
	adapter.handle(request, response, handlerMethod);
}
 
Example #3
Source File: MvcNamespaceTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testPathMatchingHandlerMappings() throws Exception {
	loadBeanDefinitions("mvc-config-path-matching-mappings.xml");

	RequestMappingHandlerMapping requestMapping = appContext.getBean(RequestMappingHandlerMapping.class);
	assertNotNull(requestMapping);
	assertEquals(TestPathHelper.class, requestMapping.getUrlPathHelper().getClass());
	assertEquals(TestPathMatcher.class, requestMapping.getPathMatcher().getClass());

	SimpleUrlHandlerMapping viewController = appContext.getBean(VIEWCONTROLLER_BEAN_NAME, SimpleUrlHandlerMapping.class);
	assertNotNull(viewController);
	assertEquals(TestPathHelper.class, viewController.getUrlPathHelper().getClass());
	assertEquals(TestPathMatcher.class, viewController.getPathMatcher().getClass());

	for (SimpleUrlHandlerMapping handlerMapping : appContext.getBeansOfType(SimpleUrlHandlerMapping.class).values()) {
		assertNotNull(handlerMapping);
		assertEquals(TestPathHelper.class, handlerMapping.getUrlPathHelper().getClass());
		assertEquals(TestPathMatcher.class, handlerMapping.getPathMatcher().getClass());
	}
}
 
Example #4
Source File: MvcNamespaceTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
private void doTestCustomValidator(String xml) throws Exception {
	loadBeanDefinitions(xml);

	RequestMappingHandlerMapping mapping = appContext.getBean(RequestMappingHandlerMapping.class);
	assertNotNull(mapping);
	assertFalse(mapping.getUrlPathHelper().shouldRemoveSemicolonContent());

	RequestMappingHandlerAdapter adapter = appContext.getBean(RequestMappingHandlerAdapter.class);
	assertNotNull(adapter);
	assertEquals(true, new DirectFieldAccessor(adapter).getPropertyValue("ignoreDefaultModelOnRedirect"));

	// default web binding initializer behavior test
	MockHttpServletRequest request = new MockHttpServletRequest();
	request.addParameter("date", "2009-10-31");
	MockHttpServletResponse response = new MockHttpServletResponse();
	adapter.handle(request, response, handlerMethod);

	assertTrue(appContext.getBean(TestValidator.class).validatorInvoked);
	assertFalse(handler.recordedValidationError);
}
 
Example #5
Source File: MvcNamespaceTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test(expected = TypeMismatchException.class)
public void testCustomConversionService() throws Exception {
	loadBeanDefinitions("mvc-config-custom-conversion-service.xml");

	RequestMappingHandlerMapping mapping = appContext.getBean(RequestMappingHandlerMapping.class);
	assertNotNull(mapping);
	mapping.setDefaultHandler(handlerMethod);

	// default web binding initializer behavior test
	MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
	request.setRequestURI("/accounts/12345");
	request.addParameter("date", "2009-10-31");
	MockHttpServletResponse response = new MockHttpServletResponse();

	HandlerExecutionChain chain = mapping.getHandler(request);
	assertEquals(1, chain.getInterceptors().length);
	assertTrue(chain.getInterceptors()[0] instanceof ConversionServiceExposingInterceptor);
	ConversionServiceExposingInterceptor interceptor = (ConversionServiceExposingInterceptor) chain.getInterceptors()[0];
	interceptor.preHandle(request, response, handler);
	assertSame(appContext.getBean("conversionService"), request.getAttribute(ConversionService.class.getName()));

	RequestMappingHandlerAdapter adapter = appContext.getBean(RequestMappingHandlerAdapter.class);
	assertNotNull(adapter);
	adapter.handle(request, response, handlerMethod);
}
 
Example #6
Source File: WebMvcConfigurationSupportTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void requestMappingHandlerMapping() throws Exception {
	ApplicationContext context = initContext(WebConfig.class, ScopedController.class, ScopedProxyController.class);
	RequestMappingHandlerMapping handlerMapping = context.getBean(RequestMappingHandlerMapping.class);
	assertEquals(0, handlerMapping.getOrder());

	HandlerExecutionChain chain = handlerMapping.getHandler(new MockHttpServletRequest("GET", "/"));
	assertNotNull(chain);
	assertNotNull(chain.getInterceptors());
	assertEquals(ConversionServiceExposingInterceptor.class, chain.getInterceptors()[0].getClass());

	chain = handlerMapping.getHandler(new MockHttpServletRequest("GET", "/scoped"));
	assertNotNull("HandlerExecutionChain for '/scoped' mapping should not be null.", chain);

	chain = handlerMapping.getHandler(new MockHttpServletRequest("GET", "/scopedProxy"));
	assertNotNull("HandlerExecutionChain for '/scopedProxy' mapping should not be null.", chain);
}
 
Example #7
Source File: WebMvcConfigurationSupportTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void requestMappingHandlerMapping() throws Exception {
	ApplicationContext context = initContext(WebConfig.class, ScopedController.class, ScopedProxyController.class);
	RequestMappingHandlerMapping handlerMapping = context.getBean(RequestMappingHandlerMapping.class);
	assertEquals(0, handlerMapping.getOrder());

	HandlerExecutionChain chain = handlerMapping.getHandler(new MockHttpServletRequest("GET", "/"));
	assertNotNull(chain);
	assertNotNull(chain.getInterceptors());
	assertEquals(ConversionServiceExposingInterceptor.class, chain.getInterceptors()[0].getClass());

	chain = handlerMapping.getHandler(new MockHttpServletRequest("GET", "/scoped"));
	assertNotNull("HandlerExecutionChain for '/scoped' mapping should not be null.", chain);

	chain = handlerMapping.getHandler(new MockHttpServletRequest("GET", "/scopedProxy"));
	assertNotNull("HandlerExecutionChain for '/scopedProxy' mapping should not be null.", chain);
}
 
Example #8
Source File: MvcNamespaceTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testContentNegotiationManager() throws Exception {
	loadBeanDefinitions("mvc-config-content-negotiation-manager.xml");

	RequestMappingHandlerMapping mapping = appContext.getBean(RequestMappingHandlerMapping.class);
	ContentNegotiationManager manager = mapping.getContentNegotiationManager();

	MockHttpServletRequest request = new MockHttpServletRequest("GET", "/foo.xml");
	NativeWebRequest webRequest = new ServletWebRequest(request);
	assertEquals(Collections.singletonList(MediaType.valueOf("application/rss+xml")),
			manager.resolveMediaTypes(webRequest));

	ViewResolverComposite compositeResolver = this.appContext.getBean(ViewResolverComposite.class);
	assertNotNull(compositeResolver);
	assertEquals("Actual: " + compositeResolver.getViewResolvers(), 1, compositeResolver.getViewResolvers().size());

	ViewResolver resolver = compositeResolver.getViewResolvers().get(0);
	assertEquals(ContentNegotiatingViewResolver.class, resolver.getClass());
	ContentNegotiatingViewResolver cnvr = (ContentNegotiatingViewResolver) resolver;
	assertSame(manager, cnvr.getContentNegotiationManager());
}
 
Example #9
Source File: MvcNamespaceTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testBeanDecoration() throws Exception {
	loadBeanDefinitions("mvc-config-bean-decoration.xml");

	RequestMappingHandlerMapping mapping = appContext.getBean(RequestMappingHandlerMapping.class);
	assertNotNull(mapping);
	mapping.setDefaultHandler(handlerMethod);

	MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");

	HandlerExecutionChain chain = mapping.getHandler(request);
	assertEquals(3, chain.getInterceptors().length);
	assertTrue(chain.getInterceptors()[0] instanceof ConversionServiceExposingInterceptor);
	assertTrue(chain.getInterceptors()[1] instanceof LocaleChangeInterceptor);
	assertTrue(chain.getInterceptors()[2] instanceof ThemeChangeInterceptor);
	LocaleChangeInterceptor interceptor = (LocaleChangeInterceptor) chain.getInterceptors()[1];
	assertEquals("lang", interceptor.getParamName());
	ThemeChangeInterceptor interceptor2 = (ThemeChangeInterceptor) chain.getInterceptors()[2];
	assertEquals("style", interceptor2.getParamName());
}
 
Example #10
Source File: MvcNamespaceTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
private void doTestCustomValidator(String xml) throws Exception {
	loadBeanDefinitions(xml);

	RequestMappingHandlerMapping mapping = appContext.getBean(RequestMappingHandlerMapping.class);
	assertNotNull(mapping);
	assertFalse(mapping.getUrlPathHelper().shouldRemoveSemicolonContent());

	RequestMappingHandlerAdapter adapter = appContext.getBean(RequestMappingHandlerAdapter.class);
	assertNotNull(adapter);
	assertEquals(true, new DirectFieldAccessor(adapter).getPropertyValue("ignoreDefaultModelOnRedirect"));

	// default web binding initializer behavior test
	MockHttpServletRequest request = new MockHttpServletRequest();
	request.addParameter("date", "2009-10-31");
	MockHttpServletResponse response = new MockHttpServletResponse();
	adapter.handle(request, response, handlerMethod);

	assertTrue(appContext.getBean(TestValidator.class).validatorInvoked);
	assertFalse(handler.recordedValidationError);
}
 
Example #11
Source File: ExposedEndpointsControllerTest.java    From blackduck-alert with Apache License 2.0 6 votes vote down vote up
@Test
public void getTest() {
    RequestMappingHandlerMapping handlerMapping = Mockito.mock(RequestMappingHandlerMapping.class);
    ExposedEndpointsController controller = new ExposedEndpointsController(new Gson(), handlerMapping);

    String endpoint1 = "/api/test";
    String endpoint2 = "/api/other/test";

    Map<RequestMappingInfo, HandlerMethod> handlerMethods = new HashMap<>();
    RequestMappingInfo info = new RequestMappingInfo(new PatternsRequestCondition(endpoint1, endpoint2), new RequestMethodsRequestCondition(RequestMethod.GET, RequestMethod.POST), null, null, null, null, null);
    handlerMethods.put(info, null);

    Mockito.when(handlerMapping.getHandlerMethods()).thenReturn(handlerMethods);

    ResponseEntity<String> responseEntity = controller.get();
    Assertions.assertTrue(StringUtils.isNotBlank(responseEntity.getBody()), "Expected the response body to contain json");
}
 
Example #12
Source File: RequestMappingService.java    From api-mock-util with Apache License 2.0 6 votes vote down vote up
public boolean hasApiRegistered(String api,String requestMethod){
    notBlank(api,"api cant not be null");
    notBlank(requestMethod,"requestMethod cant not be null");

    RequestMappingHandlerMapping requestMappingHandlerMapping = webApplicationContext.getBean(RequestMappingHandlerMapping.class);
    Map<RequestMappingInfo, HandlerMethod> map = requestMappingHandlerMapping.getHandlerMethods();
    for (RequestMappingInfo info : map.keySet()) {
        for(String pattern :info.getPatternsCondition().getPatterns()){
            if(pattern.equalsIgnoreCase(api)){ // 匹配url
                if(info.getMethodsCondition().getMethods().contains(getRequestMethod(requestMethod))){ // 匹配requestMethod
                    return true;
                }
            }
        }
    }

    return false;
}
 
Example #13
Source File: ZebraListener.java    From Zebra with MIT License 6 votes vote down vote up
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
    //获取上下文
    ServletContext sc = servletContextEvent.getServletContext();
    ApplicationContext ac = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);

    //获取Mapping(就是存放了所有的Controoler中@Path注解的Url映射)
    RequestMappingHandlerMapping mapping = ac.getBean(RequestMappingHandlerMapping.class);

    //遍历所有的handlerMethods(为了从mapping中取出Url,交给Zookeeper进行注册)
    Map<RequestMappingInfo, HandlerMethod> handlerMethods = mapping.getHandlerMethods();
    for (RequestMappingInfo key : handlerMethods.keySet()) {
        String serviceName = key.getName();
        if(!StringUtils.isEmpty(serviceName)){
            //不等于空,则拿到了服务名称,则立即注册
            registry.register(serviceName,String.format("%s:%d",serverAddress,serverPort));
        }
    }
}
 
Example #14
Source File: RequestMappingService.java    From api-mock-util with Apache License 2.0 6 votes vote down vote up
public ApiBean registerApi(String index,String api,String requestMethod,String msg){
    check(!hasMethodOccupied(index),"该序号已经被占用,请先注销api。");
    check(!hasApiRegistered(api,requestMethod),"该api已经注册过了");

    RequestMappingHandlerMapping requestMappingHandlerMapping = webApplicationContext.getBean(RequestMappingHandlerMapping.class);
    Method targetMethod = ReflectionUtils.findMethod(ApiController.class, getHandlerMethodName(index)); // 找到处理该路由的方法

    PatternsRequestCondition patternsRequestCondition = new PatternsRequestCondition(api);
    RequestMethodsRequestCondition requestMethodsRequestCondition = new RequestMethodsRequestCondition(getRequestMethod(requestMethod));

    RequestMappingInfo mapping_info = new RequestMappingInfo(patternsRequestCondition, requestMethodsRequestCondition, null, null, null, null, null);
    requestMappingHandlerMapping.registerMapping(mapping_info, "apiController", targetMethod); // 注册映射处理

    // 保存注册信息到本地
    ApiBean apiInfo = new ApiBean();
    apiInfo.setApi(api);
    apiInfo.setRequestMethod(requestMethod);
    apiInfo.setMsg(msg);
    Constants.requestMappings.put(index,apiInfo);

    return apiInfo;
}
 
Example #15
Source File: SpringMvcHomeModuleExtensionFactory.java    From crnk-framework with Apache License 2.0 6 votes vote down vote up
public static HomeModuleExtension create(String pathPrefix, Collection<RequestMappingHandlerMapping> mappings) {
	HomeModuleExtension ext = new HomeModuleExtension();

	for (RequestMappingHandlerMapping mapping : mappings) {
		Map<RequestMappingInfo, HandlerMethod> handlerMethods = mapping.getHandlerMethods();
		for (RequestMappingInfo info : handlerMethods.keySet()) {
			Set<String> patterns = info.getPatternsCondition().getPatterns();
			for (String pattern : patterns) {
				if (pattern.equals("/error") || pattern.contains("*")) {
					continue;
				}

				if (pathPrefix == null) {
					ext.addPath(pattern);
				} else if (pattern.startsWith(pathPrefix)) {
					ext.addPath(pattern.substring(pathPrefix.length()));
				}
			}
		}
	}

	return ext;
}
 
Example #16
Source File: MvcNamespaceTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testInterceptors() throws Exception {
	loadBeanDefinitions("mvc-config-interceptors.xml");

	RequestMappingHandlerMapping mapping = appContext.getBean(RequestMappingHandlerMapping.class);
	assertNotNull(mapping);
	mapping.setDefaultHandler(handlerMethod);

	MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
	request.setRequestURI("/accounts/12345");
	request.addParameter("locale", "en");
	request.addParameter("theme", "green");

	HandlerExecutionChain chain = mapping.getHandler(request);
	assertEquals(4, chain.getInterceptors().length);
	assertTrue(chain.getInterceptors()[0] instanceof ConversionServiceExposingInterceptor);
	assertTrue(chain.getInterceptors()[1] instanceof LocaleChangeInterceptor);
	assertTrue(chain.getInterceptors()[2] instanceof ThemeChangeInterceptor);
	assertTrue(chain.getInterceptors()[3] instanceof UserRoleAuthorizationInterceptor);

	request.setRequestURI("/admin/users");
	chain = mapping.getHandler(request);
	assertEquals(2, chain.getInterceptors().length);

	request.setRequestURI("/logged/accounts/12345");
	chain = mapping.getHandler(request);
	assertEquals(3, chain.getInterceptors().length);

	request.setRequestURI("/foo/logged");
	chain = mapping.getHandler(request);
	assertEquals(3, chain.getInterceptors().length);
}
 
Example #17
Source File: SpringDocApp94Test.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
@Bean
public RequestMappingHandlerMapping defaultTestHandlerMapping(GreetingController greetingController) throws NoSuchMethodException {
	RequestMappingHandlerMapping result = new RequestMappingHandlerMapping();
	RequestMappingInfo requestMappingInfo =
			RequestMappingInfo.paths("/test").methods(RequestMethod.GET).produces(MediaType.APPLICATION_JSON_VALUE).build();

	result.setApplicationContext(this.applicationContext);
	result.registerMapping(requestMappingInfo, "greetingController", GreetingController.class.getDeclaredMethod("sayHello2"));
	//result.handlerme
	return result;
}
 
Example #18
Source File: StandaloneMockMvcBuilder.java    From java-technology-stack with MIT License 5 votes vote down vote up
public RequestMappingHandlerMapping getHandlerMapping() {
	RequestMappingHandlerMapping handlerMapping = handlerMappingFactory.get();
	handlerMapping.setEmbeddedValueResolver(new StaticStringValueResolver(placeholderValues));
	handlerMapping.setUseSuffixPatternMatch(useSuffixPatternMatch);
	handlerMapping.setUseTrailingSlashMatch(useTrailingSlashPatternMatch);
	handlerMapping.setOrder(0);
	handlerMapping.setInterceptors(getInterceptors());
	if (removeSemicolonContent != null) {
		handlerMapping.setRemoveSemicolonContent(removeSemicolonContent);
	}
	return handlerMapping;
}
 
Example #19
Source File: StandaloneMockMvcBuilderTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test  // SPR-10825
public void placeHoldersInRequestMapping() throws Exception {
	TestStandaloneMockMvcBuilder builder = new TestStandaloneMockMvcBuilder(new PlaceholderController());
	builder.addPlaceholderValue("sys.login.ajax", "/foo");
	builder.build();

	RequestMappingHandlerMapping hm = builder.wac.getBean(RequestMappingHandlerMapping.class);

	MockHttpServletRequest request = new MockHttpServletRequest("GET", "/foo");
	HandlerExecutionChain chain = hm.getHandler(request);

	assertNotNull(chain);
	assertEquals("handleWithPlaceholders", ((HandlerMethod) chain.getHandler()).getMethod().getName());
}
 
Example #20
Source File: WebMvcConfigurationSupport.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Return a {@link RequestMappingHandlerMapping} ordered at 0 for mapping
 * requests to annotated controllers.
 */
@Bean
public RequestMappingHandlerMapping requestMappingHandlerMapping() {
	RequestMappingHandlerMapping handlerMapping = createRequestMappingHandlerMapping();
	handlerMapping.setOrder(0);
	handlerMapping.setInterceptors(getInterceptors());
	handlerMapping.setContentNegotiationManager(mvcContentNegotiationManager());
	handlerMapping.setCorsConfigurations(getCorsConfigurations());

	PathMatchConfigurer configurer = getPathMatchConfigurer();
	if (configurer.isUseSuffixPatternMatch() != null) {
		handlerMapping.setUseSuffixPatternMatch(configurer.isUseSuffixPatternMatch());
	}
	if (configurer.isUseRegisteredSuffixPatternMatch() != null) {
		handlerMapping.setUseRegisteredSuffixPatternMatch(configurer.isUseRegisteredSuffixPatternMatch());
	}
	if (configurer.isUseTrailingSlashMatch() != null) {
		handlerMapping.setUseTrailingSlashMatch(configurer.isUseTrailingSlashMatch());
	}
	if (configurer.getPathMatcher() != null) {
		handlerMapping.setPathMatcher(configurer.getPathMatcher());
	}
	if (configurer.getUrlPathHelper() != null) {
		handlerMapping.setUrlPathHelper(configurer.getUrlPathHelper());
	}

	return handlerMapping;
}
 
Example #21
Source File: AnnotationDrivenBeanDefinitionParserTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testPathMatchingConfiguration() {
	loadBeanDefinitions("mvc-config-path-matching.xml");
	RequestMappingHandlerMapping hm = appContext.getBean(RequestMappingHandlerMapping.class);
	assertNotNull(hm);
	assertTrue(hm.useSuffixPatternMatch());
	assertFalse(hm.useTrailingSlashMatch());
	assertTrue(hm.useRegisteredSuffixPatternMatch());
	assertThat(hm.getUrlPathHelper(), Matchers.instanceOf(TestPathHelper.class));
	assertThat(hm.getPathMatcher(), Matchers.instanceOf(TestPathMatcher.class));
	List<String> fileExtensions = hm.getContentNegotiationManager().getAllFileExtensions();
	assertThat(fileExtensions, Matchers.contains("xml"));
	assertThat(fileExtensions, Matchers.hasSize(1));
}
 
Example #22
Source File: ApiDispatcherServletConfiguration.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Override
protected RequestMappingHandlerMapping createRequestMappingHandlerMapping() {
    RequestMappingHandlerMapping requestMappingHandlerMapping = new RequestMappingHandlerMapping();
    requestMappingHandlerMapping.setUseSuffixPatternMatch(false);
    requestMappingHandlerMapping.setRemoveSemicolonContent(false);
    return requestMappingHandlerMapping;
}
 
Example #23
Source File: StandaloneMockMvcBuilder.java    From java-technology-stack with MIT License 5 votes vote down vote up
private void registerMvcSingletons(StubWebApplicationContext wac) {
	StandaloneConfiguration config = new StandaloneConfiguration();
	config.setApplicationContext(wac);
	ServletContext sc = wac.getServletContext();

	wac.addBeans(this.controllers);
	wac.addBeans(this.controllerAdvice);

	RequestMappingHandlerMapping hm = config.getHandlerMapping();
	if (sc != null) {
		hm.setServletContext(sc);
	}
	hm.setApplicationContext(wac);
	hm.afterPropertiesSet();
	wac.addBean("requestMappingHandlerMapping", hm);

	RequestMappingHandlerAdapter ha = config.requestMappingHandlerAdapter();
	if (sc != null) {
		ha.setServletContext(sc);
	}
	ha.setApplicationContext(wac);
	ha.afterPropertiesSet();
	wac.addBean("requestMappingHandlerAdapter", ha);

	wac.addBean("handlerExceptionResolver", config.handlerExceptionResolver());

	wac.addBeans(initViewResolvers(wac));
	wac.addBean(DispatcherServlet.LOCALE_RESOLVER_BEAN_NAME, this.localeResolver);
	wac.addBean(DispatcherServlet.THEME_RESOLVER_BEAN_NAME, new FixedThemeResolver());
	wac.addBean(DispatcherServlet.REQUEST_TO_VIEW_NAME_TRANSLATOR_BEAN_NAME, new DefaultRequestToViewNameTranslator());

	this.flashMapManager = new SessionFlashMapManager();
	wac.addBean(DispatcherServlet.FLASH_MAP_MANAGER_BEAN_NAME, this.flashMapManager);

	extendMvcSingletons(sc).forEach(wac::addBean);
}
 
Example #24
Source File: DelegatingWebMvcConfigurationTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@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());
}
 
Example #25
Source File: DelegatingWebMvcConfigurationTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example #26
Source File: WebMvcConfig.java    From maven-framework-project with MIT License 5 votes vote down vote up
/**
     * We mention this in the book, but this helps to ensure that the intercept-url patterns prevent access to our
     * controllers. For example, once security has been applied for administrators try commenting out the modifications
     * to the super class and requesting <a
     * href="http://localhost:800/calendar/events/.html">http://localhost:800/calendar/events/.html</a>. You will
     * observe that security is bypassed since it did not match the pattern we provided. In later chapters, we discuss
     * how to secure the service tier which helps mitigate bypassing of the URL based security too.
     */
    @Bean
    @Override
    public RequestMappingHandlerMapping requestMappingHandlerMapping() {
        RequestMappingHandlerMapping result = super.requestMappingHandlerMapping();
//        result.setUseSuffixPatternMatch(false);
        result.setUseTrailingSlashMatch(false);
        return result;
    }
 
Example #27
Source File: WebAutoConfiguration.java    From faster-framework-project with Apache License 2.0 5 votes vote down vote up
@Override
public RequestMappingHandlerMapping getRequestMappingHandlerMapping() {
    if (versionProperties.isEnabled()) {
        return new ApiRequestMappingHandlerMapping(versionProperties.getMinimumVersion(), versionProperties.isParsePackageVersion());
    } else {
        return null;
    }
}
 
Example #28
Source File: HandlerMappingIntrospectorTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
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 #29
Source File: RaptorServiceAutoConfiguration.java    From raptor with Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnBean(RequestMappingHandlerMapping.class)
public RaptorProtoFilesEndpoint createRaptorProtoFilesEndpoint(RequestMappingHandlerMapping requestMappingHandlerMapping) {
    RaptorProtoFilesEndpoint raptorProtoFilesEndpoint = new RaptorProtoFilesEndpoint(requestMappingHandlerMapping);
    raptorProtoFilesEndpoint.setClassLoader(classLoader);
    return raptorProtoFilesEndpoint;
}
 
Example #30
Source File: WebMvcConfigurationSupport.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Return a {@link RequestMappingHandlerMapping} ordered at 0 for mapping
 * requests to annotated controllers.
 */
@Bean
public RequestMappingHandlerMapping requestMappingHandlerMapping() {
	RequestMappingHandlerMapping mapping = createRequestMappingHandlerMapping();
	mapping.setOrder(0);
	mapping.setInterceptors(getInterceptors());
	mapping.setContentNegotiationManager(mvcContentNegotiationManager());
	mapping.setCorsConfigurations(getCorsConfigurations());

	PathMatchConfigurer configurer = getPathMatchConfigurer();

	Boolean useSuffixPatternMatch = configurer.isUseSuffixPatternMatch();
	if (useSuffixPatternMatch != null) {
		mapping.setUseSuffixPatternMatch(useSuffixPatternMatch);
	}
	Boolean useRegisteredSuffixPatternMatch = configurer.isUseRegisteredSuffixPatternMatch();
	if (useRegisteredSuffixPatternMatch != null) {
		mapping.setUseRegisteredSuffixPatternMatch(useRegisteredSuffixPatternMatch);
	}
	Boolean useTrailingSlashMatch = configurer.isUseTrailingSlashMatch();
	if (useTrailingSlashMatch != null) {
		mapping.setUseTrailingSlashMatch(useTrailingSlashMatch);
	}

	UrlPathHelper pathHelper = configurer.getUrlPathHelper();
	if (pathHelper != null) {
		mapping.setUrlPathHelper(pathHelper);
	}
	PathMatcher pathMatcher = configurer.getPathMatcher();
	if (pathMatcher != null) {
		mapping.setPathMatcher(pathMatcher);
	}
	Map<String, Predicate<Class<?>>> pathPrefixes = configurer.getPathPrefixes();
	if (pathPrefixes != null) {
		mapping.setPathPrefixes(pathPrefixes);
	}

	return mapping;
}