@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); }
/** * 请求是否支持访问日志记录 * @param request * @return */ protected boolean isRequestSupport(HttpServletRequest request) { try { if(!this.isAsyncDispatch(request) && !this.isAsyncStarted(request)){ HandlerExecutionChain handlerExecutionChain = this.getSpringMvcHandlerMethodMapping().getHandler(request); if(handlerExecutionChain != null && handlerExecutionChain.getHandler() != null && handlerExecutionChain.getHandler() instanceof HandlerMethod){ HandlerMethod handlerMethod = (HandlerMethod) handlerExecutionChain.getHandler(); HttpAccessLogging httpAccessLogging = handlerMethod.getMethodAnnotation(HttpAccessLogging.class); return httpAccessLogging != null; } } } catch (Exception e) { logger.error(e.getMessage(), e); } return false; }
/** * Look up a handler for the given request, falling back to the default * handler if no specific one is found. * @param request current HTTP request * @return the corresponding handler instance, or the default handler * @see #getHandlerInternal */ @Override public final HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception { Object handler = getHandlerInternal(request); if (handler == null) { handler = getDefaultHandler(); } if (handler == null) { return null; } // Bean name or resolved handler? if (handler instanceof String) { String handlerName = (String) handler; handler = getApplicationContext().getBean(handlerName); } HandlerExecutionChain executionChain = getHandlerExecutionChain(handler, request); if (CorsUtils.isCorsRequest(request)) { CorsConfiguration globalConfig = this.corsConfigSource.getCorsConfiguration(request); CorsConfiguration handlerConfig = getCorsConfiguration(handler, request); CorsConfiguration config = (globalConfig != null ? globalConfig.combine(handlerConfig) : handlerConfig); executionChain = getCorsHandlerExecutionChain(request, executionChain, config); } return executionChain; }
@Test public void preFlightRequest() throws Exception { this.handlerMapping.registerHandler(new MethodLevelController()); this.request.setMethod("OPTIONS"); this.request.addHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET"); this.request.setRequestURI("/default"); HandlerExecutionChain chain = this.handlerMapping.getHandler(request); CorsConfiguration config = getCorsConfiguration(chain, true); assertNotNull(config); assertArrayEquals(new String[]{"GET"}, config.getAllowedMethods().toArray()); assertArrayEquals(new String[]{"*"}, config.getAllowedOrigins().toArray()); assertTrue(config.getAllowCredentials()); assertArrayEquals(new String[]{"*"}, config.getAllowedHeaders().toArray()); assertTrue(CollectionUtils.isEmpty(config.getExposedHeaders())); assertEquals(new Long(1800), config.getMaxAge()); }
@Test public void ambiguousHeaderPreFlightRequest() throws Exception { this.handlerMapping.registerHandler(new MethodLevelController()); this.request.setMethod("OPTIONS"); this.request.addHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET"); this.request.addHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS, "header1"); this.request.setRequestURI("/ambiguous-header"); HandlerExecutionChain chain = this.handlerMapping.getHandler(request); CorsConfiguration config = getCorsConfiguration(chain, true); assertNotNull(config); assertArrayEquals(new String[]{"*"}, config.getAllowedMethods().toArray()); assertArrayEquals(new String[]{"*"}, config.getAllowedOrigins().toArray()); assertArrayEquals(new String[]{"*"}, config.getAllowedHeaders().toArray()); assertTrue(config.getAllowCredentials()); assertTrue(CollectionUtils.isEmpty(config.getExposedHeaders())); assertNull(config.getMaxAge()); }
@Test public void ambiguousProducesPreFlightRequest() throws Exception { this.handlerMapping.registerHandler(new MethodLevelController()); this.request.setMethod("OPTIONS"); this.request.addHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET"); this.request.setRequestURI("/ambiguous-produces"); HandlerExecutionChain chain = this.handlerMapping.getHandler(request); CorsConfiguration config = getCorsConfiguration(chain, true); assertNotNull(config); assertArrayEquals(new String[]{"*"}, config.getAllowedMethods().toArray()); assertArrayEquals(new String[]{"*"}, config.getAllowedOrigins().toArray()); assertArrayEquals(new String[]{"*"}, config.getAllowedHeaders().toArray()); assertTrue(config.getAllowCredentials()); assertTrue(CollectionUtils.isEmpty(config.getExposedHeaders())); assertNull(config.getMaxAge()); }
@Test public void testRequestMappingMethod() throws Exception { String datePattern = "MM:dd:yyyy"; SimpleDateFormat dateFormat = new SimpleDateFormat(datePattern); String dateA = "11:01:2011"; String dateB = "11:02:2011"; MockHttpServletRequest request = new MockHttpServletRequest("POST", "/path1/path2"); request.setParameter("datePattern", datePattern); request.addHeader("header1", dateA); request.addHeader("header2", dateB); HandlerExecutionChain chain = handlerMapping.getHandler(request); assertNotNull(chain); ModelAndView mav = handlerAdapter.handle(request, new MockHttpServletResponse(), chain.getHandler()); assertEquals("model attr1:", dateFormat.parse(dateA), mav.getModel().get("attr1")); assertEquals("model attr2:", dateFormat.parse(dateB), mav.getModel().get("attr2")); MockHttpServletResponse response = new MockHttpServletResponse(); exceptionResolver.resolveException(request, response, chain.getHandler(), new Exception("failure")); assertEquals("text/plain;charset=ISO-8859-1", response.getHeader("Content-Type")); assertEquals("failure", response.getContentAsString()); }
@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 requestsWithHandlers() throws Exception { Object bean = wac.getBean("mainController"); MockHttpServletRequest req = new MockHttpServletRequest("GET", "/welcome.html"); HandlerExecutionChain hec = getHandler(req); assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean); req = new MockHttpServletRequest("GET", "/show.html"); hec = getHandler(req); assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean); req = new MockHttpServletRequest("GET", "/bookseats.html"); hec = getHandler(req); assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean); }
@Test public void testNewlineInRequest() throws Exception { SimpleUrlHandlerMapping handlerMapping = new SimpleUrlHandlerMapping(); handlerMapping.setUrlDecode(false); Object controller = new Object(); Map<String, Object> urlMap = new LinkedHashMap<String, Object>(); urlMap.put("/*/baz", controller); handlerMapping.setUrlMap(urlMap); handlerMapping.setApplicationContext(new StaticApplicationContext()); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/foo%0a%0dbar/baz"); HandlerExecutionChain hec = handlerMapping.getHandler(request); assertNotNull(hec); assertSame(controller, hec.getHandler()); }
@Test public void asteriskMatches() throws Exception { HandlerMapping hm = (HandlerMapping) wac.getBean("handlerMapping"); Object bean = wac.getBean("godCtrl"); MockHttpServletRequest req = new MockHttpServletRequest("GET", "/mypath/test.html"); HandlerExecutionChain hec = hm.getHandler(req); assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean); req = new MockHttpServletRequest("GET", "/mypath/testarossa"); hec = hm.getHandler(req); assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean); req = new MockHttpServletRequest("GET", "/mypath/tes"); hec = hm.getHandler(req); assertTrue("Handler is correct bean", hec == null); }
@Test public void overlappingMappings() throws Exception { BeanNameUrlHandlerMapping hm = (BeanNameUrlHandlerMapping) wac.getBean("handlerMapping"); Object anotherHandler = new Object(); hm.registerHandler("/mypath/testaross*", anotherHandler); Object bean = wac.getBean("godCtrl"); MockHttpServletRequest req = new MockHttpServletRequest("GET", "/mypath/test.html"); HandlerExecutionChain hec = hm.getHandler(req); assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean); req = new MockHttpServletRequest("GET", "/mypath/testarossa"); hec = hm.getHandler(req); assertTrue("Handler is correct bean", hec != null && hec.getHandler() == anotherHandler); req = new MockHttpServletRequest("GET", "/mypath/tes"); hec = hm.getHandler(req); assertTrue("Handler is correct bean", hec == null); }
@Test public void actualRequestWithMappedCorsConfiguration() throws Exception { CorsConfiguration config = new CorsConfiguration(); config.addAllowedOrigin("*"); this.handlerMapping.setCorsConfigurations(Collections.singletonMap("/foo", config)); this.request.setMethod(RequestMethod.GET.name()); this.request.setRequestURI("/foo"); this.request.addHeader(HttpHeaders.ORIGIN, "http://domain2.com"); this.request.addHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET"); HandlerExecutionChain chain = handlerMapping.getHandler(this.request); assertNotNull(chain); assertTrue(chain.getHandler() instanceof SimpleHandler); config = getCorsConfiguration(chain, false); assertNotNull(config); assertArrayEquals(config.getAllowedOrigins().toArray(), new String[]{"*"}); }
@Test public void preflightRequestWithMappedCorsConfiguration() throws Exception { CorsConfiguration config = new CorsConfiguration(); config.addAllowedOrigin("*"); this.handlerMapping.setCorsConfigurations(Collections.singletonMap("/foo", config)); this.request.setMethod(RequestMethod.OPTIONS.name()); this.request.setRequestURI("/foo"); this.request.addHeader(HttpHeaders.ORIGIN, "http://domain2.com"); this.request.addHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET"); HandlerExecutionChain chain = handlerMapping.getHandler(this.request); assertNotNull(chain); assertNotNull(chain.getHandler()); assertTrue(chain.getHandler().getClass().getSimpleName().equals("PreFlightHandler")); config = getCorsConfiguration(chain, true); assertNotNull(config); assertArrayEquals(config.getAllowedOrigins().toArray(), new String[]{"*"}); }
@Test public void testDefaultServletHandler() throws Exception { loadBeanDefinitions("mvc-config-default-servlet.xml", 6); HttpRequestHandlerAdapter adapter = appContext.getBean(HttpRequestHandlerAdapter.class); assertNotNull(adapter); DefaultServletHttpRequestHandler handler = appContext.getBean(DefaultServletHttpRequestHandler.class); assertNotNull(handler); SimpleUrlHandlerMapping mapping = appContext.getBean(SimpleUrlHandlerMapping.class); assertNotNull(mapping); assertEquals(Ordered.LOWEST_PRECEDENCE, mapping.getOrder()); MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI("/foo.css"); request.setMethod("GET"); HandlerExecutionChain chain = mapping.getHandler(request); assertTrue(chain.getHandler() instanceof DefaultServletHttpRequestHandler); MockHttpServletResponse response = new MockHttpServletResponse(); ModelAndView mv = adapter.handle(request, response, chain.getHandler()); assertNull(mv); }
@Test public void testDefaultServletHandlerWithOptionalAttributes() throws Exception { loadBeanDefinitions("mvc-config-default-servlet-optional-attrs.xml", 6); HttpRequestHandlerAdapter adapter = appContext.getBean(HttpRequestHandlerAdapter.class); assertNotNull(adapter); DefaultServletHttpRequestHandler handler = appContext.getBean(DefaultServletHttpRequestHandler.class); assertNotNull(handler); SimpleUrlHandlerMapping mapping = appContext.getBean(SimpleUrlHandlerMapping.class); assertNotNull(mapping); assertEquals(Ordered.LOWEST_PRECEDENCE, mapping.getOrder()); MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI("/foo.css"); request.setMethod("GET"); HandlerExecutionChain chain = mapping.getHandler(request); assertTrue(chain.getHandler() instanceof DefaultServletHttpRequestHandler); MockHttpServletResponse response = new MockHttpServletResponse(); ModelAndView mv = adapter.handle(request, response, chain.getHandler()); assertNull(mv); }
@Test public void testBeanDecoration() throws Exception { loadBeanDefinitions("mvc-config-bean-decoration.xml", 16); 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()); }
@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); }
@Test public void suffixPatternMatch() throws Exception { TestStandaloneMockMvcBuilder builder = new TestStandaloneMockMvcBuilder(new PersonController()); builder.setUseSuffixPatternMatch(false); builder.build(); RequestMappingHandlerMapping hm = builder.wac.getBean(RequestMappingHandlerMapping.class); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/persons"); HandlerExecutionChain chain = hm.getHandler(request); assertNotNull(chain); assertEquals("persons", ((HandlerMethod) chain.getHandler()).getMethod().getName()); request = new MockHttpServletRequest("GET", "/persons.xml"); chain = hm.getHandler(request); assertNull(chain); }
@Override public HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception { if (this.mappings == null) { this.mappings = extractMappings(); } for (HandlerMapping mapping : this.mappings) { HandlerExecutionChain handler = mapping.getHandler(request); if (handler != null) { return handler; } } return null; }
protected HandlerExecutionChain getHandlerExecution(HttpServletRequest request) throws Exception { WebApplicationContext appContext = WebApplicationContextUtils .getRequiredWebApplicationContext(request.getServletContext()); HandlerMapping bean = appContext.getBean(RequestMappingHandlerMapping.class); HandlerExecutionChain handler = bean.getHandler(request); if (handler == null) { ServletContext servletContext = request.getServletContext(); Enumeration<?> attrNameEnum = servletContext.getAttributeNames(); while (attrNameEnum.hasMoreElements()) { String attrName = (String) attrNameEnum.nextElement(); if (attrName.startsWith(FrameworkServlet.SERVLET_CONTEXT_PREFIX)) { appContext = (WebApplicationContext) servletContext.getAttribute(attrName); bean = appContext.getBean(RequestMappingHandlerMapping.class); handler = bean.getHandler(request); if (handler != null) { break; } } } } return handler; }
@Test public void testExporter() throws Exception { try { logger.info("stressTestExporter: testing RPC"); HttpServletRequest serviceRequest = getServiceRequest(); HandlerExecutionChain chain = handlerMapping.getHandler(serviceRequest); GWTRPCServiceExporter exporter = (GWTRPCServiceExporter) chain.getHandler(); long start = System.currentTimeMillis(); for (int i = 0; i < testCount; i++) { MockHttpServletResponse serviceResponse = getServiceResponse(); exporter.handleRequest(serviceRequest, serviceResponse); String sResponse = serviceResponse.getContentAsString(); assertEquals(responsePayload, sResponse); } long end = System.currentTimeMillis(); logger.info("stressTestExporter: " + testCount + " invocations in " + (end - start) + " ms"); } catch (Throwable t) { logger.error(t.getMessage(), t); fail(); } }
/** * Look up a handler for the given request, falling back to the default * handler if no specific one is found. * @param request current HTTP request * @return the corresponding handler instance, or the default handler * @see #getHandlerInternal */ public final HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception { Object handler = getHandlerInternal(request); if (handler == null) { handler = getDefaultHandler(); } if (handler == null) { return null; } // Bean name or resolved handler? if (handler instanceof String) { String handlerName = (String) handler; handler = getApplicationContext().getBean(handlerName); } return getHandlerExecutionChain(handler, request); }
@Test public void testRequestMappingMethod() throws Exception { String datePattern = "MM:dd:yyyy"; SimpleDateFormat dateFormat = new SimpleDateFormat(datePattern); String dateA = "11:01:2011"; String dateB = "11:02:2011"; MockHttpServletRequest request = new MockHttpServletRequest("POST", "/path1/path2"); request.setParameter("datePattern", datePattern); request.addHeader("header1", dateA); request.addHeader("header2", dateB); HandlerExecutionChain chain = handlerMapping.getHandler(request); assertNotNull(chain); ModelAndView mav = handlerAdapter.handle(request, new MockHttpServletResponse(), chain.getHandler()); assertEquals(mav.getModel().get("attr1"), dateFormat.parse(dateA)); assertEquals(mav.getModel().get("attr2"), dateFormat.parse(dateB)); MockHttpServletResponse response = new MockHttpServletResponse(); exceptionResolver.resolveException(request, response, chain.getHandler(), new Exception("failure")); assertEquals("text/plain;charset=ISO-8859-1", response.getHeader("Content-Type")); assertEquals("failure", response.getContentAsString()); }
public void testAsteriskMatches() throws Exception { HandlerMapping hm = (HandlerMapping) wac.getBean("handlerMapping"); Object bean = wac.getBean("godCtrl"); MockHttpServletRequest req = new MockHttpServletRequest("GET", "/mypath/test.html"); HandlerExecutionChain hec = hm.getHandler(req); assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean); req = new MockHttpServletRequest("GET", "/mypath/testarossa"); hec = hm.getHandler(req); assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean); req = new MockHttpServletRequest("GET", "/mypath/tes"); hec = hm.getHandler(req); assertTrue("Handler is correct bean", hec == null); }
public void testOverlappingMappings() throws Exception { BeanNameUrlHandlerMapping hm = (BeanNameUrlHandlerMapping) wac.getBean("handlerMapping"); Object anotherHandler = new Object(); hm.registerHandler("/mypath/testaross*", anotherHandler); Object bean = wac.getBean("godCtrl"); MockHttpServletRequest req = new MockHttpServletRequest("GET", "/mypath/test.html"); HandlerExecutionChain hec = hm.getHandler(req); assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean); req = new MockHttpServletRequest("GET", "/mypath/testarossa"); hec = hm.getHandler(req); assertTrue("Handler is correct bean", hec != null && hec.getHandler() == anotherHandler); req = new MockHttpServletRequest("GET", "/mypath/tes"); hec = hm.getHandler(req); assertTrue("Handler is correct bean", hec == null); }
@Test(expected=TypeMismatchException.class) public void testCustomConversionService() throws Exception { loadBeanDefinitions("mvc-config-custom-conversion-service.xml", 12); 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); }
@Test public void testDefaultServletHandler() throws Exception { loadBeanDefinitions("mvc-config-default-servlet.xml", 5); HttpRequestHandlerAdapter adapter = appContext.getBean(HttpRequestHandlerAdapter.class); assertNotNull(adapter); DefaultServletHttpRequestHandler handler = appContext.getBean(DefaultServletHttpRequestHandler.class); assertNotNull(handler); SimpleUrlHandlerMapping mapping = appContext.getBean(SimpleUrlHandlerMapping.class); assertNotNull(mapping); assertEquals(Ordered.LOWEST_PRECEDENCE, mapping.getOrder()); MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI("/foo.css"); request.setMethod("GET"); HandlerExecutionChain chain = mapping.getHandler(request); assertTrue(chain.getHandler() instanceof DefaultServletHttpRequestHandler); MockHttpServletResponse response = new MockHttpServletResponse(); ModelAndView mv = adapter.handle(request, response, chain.getHandler()); assertNull(mv); }
@Test public void testDefaultServletHandlerWithOptionalAttributes() throws Exception { loadBeanDefinitions("mvc-config-default-servlet-optional-attrs.xml", 5); HttpRequestHandlerAdapter adapter = appContext.getBean(HttpRequestHandlerAdapter.class); assertNotNull(adapter); DefaultServletHttpRequestHandler handler = appContext.getBean(DefaultServletHttpRequestHandler.class); assertNotNull(handler); SimpleUrlHandlerMapping mapping = appContext.getBean(SimpleUrlHandlerMapping.class); assertNotNull(mapping); assertEquals(Ordered.LOWEST_PRECEDENCE, mapping.getOrder()); MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI("/foo.css"); request.setMethod("GET"); HandlerExecutionChain chain = mapping.getHandler(request); assertTrue(chain.getHandler() instanceof DefaultServletHttpRequestHandler); MockHttpServletResponse response = new MockHttpServletResponse(); ModelAndView mv = adapter.handle(request, response, chain.getHandler()); assertNull(mv); }
@Test public void testBeanDecoration() throws Exception { loadBeanDefinitions("mvc-config-bean-decoration.xml", 14); 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()); }
@Test public void beanNameHandlerMapping() throws Exception { StaticWebApplicationContext cxt = new StaticWebApplicationContext(); cxt.registerSingleton("/controller", TestController.class); HttpServletRequest request = new MockHttpServletRequest("GET", "/controller"); BeanNameUrlHandlerMapping handlerMapping = mvcConfiguration.beanNameHandlerMapping(); assertEquals(2, handlerMapping.getOrder()); handlerMapping.setApplicationContext(cxt); HandlerExecutionChain chain = handlerMapping.getHandler(request); assertNotNull(chain.getInterceptors()); assertEquals(2, chain.getInterceptors().length); assertEquals(ConversionServiceExposingInterceptor.class, chain.getInterceptors()[1].getClass()); }
/** * Passes the given request to a proper controller. * * @param request * @return * @throws Exception */ public MockHttpServletResponse handle(HttpServletRequest request) throws Exception { MockHttpServletResponse response = new MockHttpServletResponse(); HandlerExecutionChain handlerExecutionChain = null; for (DefaultAnnotationHandlerMapping handlerMapping : handlerMappings) { handlerExecutionChain = handlerMapping.getHandler(request); if (handlerExecutionChain != null) { break; } } Assert.assertNotNull("The request URI does not exist", handlerExecutionChain); handlerAdapter.handle(request, response, handlerExecutionChain.getHandler()); return response; }
public void testShouldMergeInterceptors() throws Throwable { HandlerInterceptor interceptorOfFramework = new HandlerInterceptorSub(); HandlerInterceptor interceptorOfTab = new HandlerInterceptorSub(); HandlerInterceptor[] interceptorsOfFramework = new HandlerInterceptor[] {interceptorOfFramework}; HandlerInterceptor[] interceptorsOfTab = new HandlerInterceptor[] {interceptorOfTab}; Mock proceedingJoinPoint = mock(ProceedingJoinPoint.class); proceedingJoinPoint.expects(once()).method("proceed").will( returnValue(new HandlerExecutionChain(null, interceptorsOfTab))); InterceptorInjector injector = new InterceptorInjector(); injector.setInterceptors(interceptorsOfFramework); HandlerExecutionChain handlers = injector.mergeInterceptorsToTabs((ProceedingJoinPoint) proceedingJoinPoint.proxy()); assertEquals(2, handlers.getInterceptors().length); assertSame(interceptorOfFramework, handlers.getInterceptors()[0]); assertSame(interceptorOfTab, handlers.getInterceptors()[1]); }
public void testShouldJustReturnInterceptorsOfFrameworkIfNoTabInterceptors() throws Throwable { HandlerInterceptor interceptorOfFramework = new HandlerInterceptorSub(); HandlerInterceptor[] interceptorsOfFramework = new HandlerInterceptor[] {interceptorOfFramework}; Mock proceedingJoinPoint = mock(ProceedingJoinPoint.class); proceedingJoinPoint.expects(once()).method("proceed").will( returnValue(new HandlerExecutionChain(null, null))); InterceptorInjector injector = new InterceptorInjector(); injector.setInterceptors(interceptorsOfFramework); HandlerExecutionChain handlers = injector.mergeInterceptorsToTabs((ProceedingJoinPoint) proceedingJoinPoint.proxy()); assertEquals(1, handlers.getInterceptors().length); assertSame(interceptorOfFramework, handlers.getInterceptors()[0]); }
public Map<String, Object> runHandler(HttpServletRequest req, HttpServletResponse resp, String pageUrl, String url) throws Exception { Map<String, String> params = new HashMap<String, String>(); if (pageUrl != null) params.put(ReqConst.PARAM_PAGE_URL, pageUrl); WinletRequestWrapper wreq = new WinletRequestWrapper(req, null, params, null); wreq.setServletPath(url); HandlerExecutionChain mappedHandler = getHandler(wreq); ModelAndView mv = getHandlerAdapter(mappedHandler.getHandler()).handle( wreq, resp, mappedHandler.getHandler()); return mv.getModel(); }
/** * Retrieve the CORS configuration for the given handler. * @param handler the handler to check (never {@code null}). * @param request the current request. * @return the CORS configuration for the handler or {@code null}. * @since 4.2 */ protected CorsConfiguration getCorsConfiguration(Object handler, HttpServletRequest request) { if (handler instanceof HandlerExecutionChain) { handler = ((HandlerExecutionChain) handler).getHandler(); } if (handler instanceof CorsConfigurationSource) { return ((CorsConfigurationSource) handler).getCorsConfiguration(request); } return null; }
@Test public void withContextPath() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myapp/welcome"); request.setContextPath("/myapp"); HandlerExecutionChain chain = this.hm.getHandler(request); assertEquals(this.wac.getBean("welcome"), chain.getHandler()); }