@Test @Deprecated public void test() throws Exception { AnnotationMethodHandlerAdapter adapter = new AnnotationMethodHandlerAdapter(); ConfigurableWebBindingInitializer binder = new ConfigurableWebBindingInitializer(); GenericConversionService service = new DefaultConversionService(); service.addConverter(new ColorConverter()); binder.setConversionService(service); adapter.setWebBindingInitializer(binder); Spr7766Controller controller = new Spr7766Controller(); MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI("/colors"); request.setPathInfo("/colors"); request.addParameter("colors", "#ffffff,000000"); MockHttpServletResponse response = new MockHttpServletResponse(); adapter.handle(request, response, controller); }
@Before public void setup() throws Exception { ConfigurableWebBindingInitializer bindingInitializer = new ConfigurableWebBindingInitializer(); bindingInitializer.setValidator(new StubValidator()); List<HandlerMethodArgumentResolver> customResolvers = new ArrayList<HandlerMethodArgumentResolver>(); customResolvers.add(new ServletWebArgumentResolverAdapter(new ColorArgumentResolver())); GenericWebApplicationContext context = new GenericWebApplicationContext(); context.refresh(); handlerAdapter = new RequestMappingHandlerAdapter(); handlerAdapter.setWebBindingInitializer(bindingInitializer); handlerAdapter.setCustomArgumentResolvers(customResolvers); handlerAdapter.setApplicationContext(context); handlerAdapter.setBeanFactory(context.getBeanFactory()); handlerAdapter.afterPropertiesSet(); request = new MockHttpServletRequest(); response = new MockHttpServletResponse(); request.setMethod("POST"); // Expose request to the current thread (for SpEL expressions) RequestContextHolder.setRequestAttributes(new ServletWebRequest(request)); }
@Test public void typeNestedSetBinding() throws Exception { initServlet(new ApplicationContextInitializer<GenericWebApplicationContext>() { @Override public void initialize(GenericWebApplicationContext context) { RootBeanDefinition csDef = new RootBeanDefinition(FormattingConversionServiceFactoryBean.class); csDef.getPropertyValues().add("converters", new TestBeanConverter()); RootBeanDefinition wbiDef = new RootBeanDefinition(ConfigurableWebBindingInitializer.class); wbiDef.getPropertyValues().add("conversionService", csDef); RootBeanDefinition adapterDef = new RootBeanDefinition(RequestMappingHandlerAdapter.class); adapterDef.getPropertyValues().add("webBindingInitializer", wbiDef); context.registerBeanDefinition("handlerAdapter", adapterDef); } }, NestedSetController.class); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myPath.do"); request.addParameter("testBeanSet", new String[] {"1", "2"}); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); assertEquals("[1, 2]-org.springframework.tests.sample.beans.TestBean", response.getContentAsString()); }
@Test public void pathVariableWithCustomConverter() throws Exception { initServlet(new ApplicationContextInitializer<GenericWebApplicationContext>() { @Override public void initialize(GenericWebApplicationContext context) { RootBeanDefinition csDef = new RootBeanDefinition(FormattingConversionServiceFactoryBean.class); csDef.getPropertyValues().add("converters", new AnnotatedExceptionRaisingConverter()); RootBeanDefinition wbiDef = new RootBeanDefinition(ConfigurableWebBindingInitializer.class); wbiDef.getPropertyValues().add("conversionService", csDef); RootBeanDefinition adapterDef = new RootBeanDefinition(RequestMappingHandlerAdapter.class); adapterDef.getPropertyValues().add("webBindingInitializer", wbiDef); context.registerBeanDefinition("handlerAdapter", adapterDef); } }, PathVariableWithCustomConverterController.class); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myPath/1"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); assertEquals(404, response.getStatus()); }
@Test public void parameterCsvAsStringArray() throws Exception { initServlet(new ApplicationContextInitializer<GenericWebApplicationContext>() { @Override public void initialize(GenericWebApplicationContext wac) { RootBeanDefinition csDef = new RootBeanDefinition(FormattingConversionServiceFactoryBean.class); RootBeanDefinition wbiDef = new RootBeanDefinition(ConfigurableWebBindingInitializer.class); wbiDef.getPropertyValues().add("conversionService", csDef); RootBeanDefinition adapterDef = new RootBeanDefinition(RequestMappingHandlerAdapter.class); adapterDef.getPropertyValues().add("webBindingInitializer", wbiDef); wac.registerBeanDefinition("handlerAdapter", adapterDef); } }, CsvController.class); MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI("/integerArray"); request.setMethod("POST"); request.addParameter("content", "1,2"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); assertEquals("1-2", response.getContentAsString()); }
@Before public void setUp() throws Exception { this.processor = new ServletModelAttributeMethodProcessor(false); Method method = getClass().getDeclaredMethod("modelAttribute", TestBean.class, TestBeanWithoutStringConstructor.class, Optional.class); this.testBeanModelAttr = new MethodParameter(method, 0); this.testBeanWithoutStringConstructorModelAttr = new MethodParameter(method, 1); this.testBeanWithOptionalModelAttr = new MethodParameter(method, 2); ConfigurableWebBindingInitializer initializer = new ConfigurableWebBindingInitializer(); initializer.setConversionService(new DefaultConversionService()); this.binderFactory = new ServletRequestDataBinderFactory(null, initializer); this.mavContainer = new ModelAndViewContainer(); this.request = new MockHttpServletRequest(); this.webRequest = new ServletWebRequest(request); }
@Test public void requestMappingHandlerAdapter() throws Exception { delegatingConfig.setConfigurers(Arrays.asList(webMvcConfigurer)); RequestMappingHandlerAdapter adapter = delegatingConfig.requestMappingHandlerAdapter(); ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer) adapter.getWebBindingInitializer(); ConversionService initializerConversionService = initializer.getConversionService(); assertTrue(initializer.getValidator() instanceof LocalValidatorFactoryBean); verify(webMvcConfigurer).configureMessageConverters(converters.capture()); verify(webMvcConfigurer).configureContentNegotiation(contentNegotiationConfigurer.capture()); verify(webMvcConfigurer).addFormatters(conversionService.capture()); verify(webMvcConfigurer).addArgumentResolvers(resolvers.capture()); verify(webMvcConfigurer).addReturnValueHandlers(handlers.capture()); verify(webMvcConfigurer).configureAsyncSupport(asyncConfigurer.capture()); assertSame(conversionService.getValue(), initializerConversionService); assertEquals(0, resolvers.getValue().size()); assertEquals(0, handlers.getValue().size()); assertEquals(converters.getValue(), adapter.getMessageConverters()); assertNotNull(asyncConfigurer); }
@Test @SuppressWarnings("rawtypes") public void resolveOptional() throws Exception { ConfigurableWebBindingInitializer initializer = new ConfigurableWebBindingInitializer(); initializer.setConversionService(new DefaultConversionService()); WebDataBinderFactory binderFactory = new DefaultDataBinderFactory(initializer); Object result = resolver.resolveArgument(paramOptional, null, webRequest, binderFactory); assertEquals(Optional.class, result.getClass()); assertEquals(Optional.empty(), result); this.request.addParameter("name", "123"); result = resolver.resolveArgument(paramOptional, null, webRequest, binderFactory); assertEquals(Optional.class, result.getClass()); assertEquals(123, ((Optional) result).get()); }
@Before public void setup() throws Exception { ConfigurableWebBindingInitializer bindingInitializer = new ConfigurableWebBindingInitializer(); bindingInitializer.setValidator(new StubValidator()); List<HandlerMethodArgumentResolver> customResolvers = new ArrayList<HandlerMethodArgumentResolver>(); customResolvers.add(new ServletWebArgumentResolverAdapter(new ColorArgumentResolver())); GenericWebApplicationContext context = new GenericWebApplicationContext(); context.refresh(); handlerAdapter = new RequestMappingHandlerAdapter(); handlerAdapter.setWebBindingInitializer(bindingInitializer); handlerAdapter.setCustomArgumentResolvers(customResolvers); handlerAdapter.setApplicationContext(context); handlerAdapter.setBeanFactory(context.getBeanFactory()); handlerAdapter.afterPropertiesSet(); request = new MockHttpServletRequest(); response = new MockHttpServletResponse(); // Expose request to the current thread (for SpEL expressions) RequestContextHolder.setRequestAttributes(new ServletWebRequest(request)); }
@Before public void setUp() throws Exception { this.processor = new ServletModelAttributeMethodProcessor(false); Method method = getClass().getDeclaredMethod("modelAttribute", TestBean.class, TestBeanWithoutStringConstructor.class); this.testBeanModelAttr = new MethodParameter(method, 0); this.testBeanWithoutStringConstructorModelAttr = new MethodParameter(method, 1); ConfigurableWebBindingInitializer initializer = new ConfigurableWebBindingInitializer(); initializer.setConversionService(new DefaultConversionService()); this.binderFactory = new ServletRequestDataBinderFactory(null, initializer ); this.mavContainer = new ModelAndViewContainer(); this.request = new MockHttpServletRequest(); this.webRequest = new ServletWebRequest(request); }
@Test public void requestMappingHandlerAdapter() throws Exception { RequestMappingHandlerAdapter adapter = mvcConfiguration.requestMappingHandlerAdapter(); List<HttpMessageConverter<?>> expectedConverters = new ArrayList<HttpMessageConverter<?>>(); mvcConfiguration.addDefaultHttpMessageConverters(expectedConverters); assertEquals(expectedConverters.size(), adapter.getMessageConverters().size()); ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer) adapter.getWebBindingInitializer(); assertNotNull(initializer); ConversionService conversionService = initializer.getConversionService(); assertNotNull(conversionService); assertTrue(conversionService instanceof FormattingConversionService); Validator validator = initializer.getValidator(); assertNotNull(validator); assertTrue(validator instanceof LocalValidatorFactoryBean); }
@Override @SuppressWarnings("unchecked") public <T> T provide(Method method, int parameterIndex) { MethodParameter methodParameter = new MethodParameter(method, parameterIndex); ModelAndViewContainer modelAndViewContainer = new ModelAndViewContainer(); NativeWebRequest webRequest = new ServletWebRequest(request); DefaultDataBinderFactory binderFactory = new DefaultDataBinderFactory(new ConfigurableWebBindingInitializer()); try { return (T) argumentResolvers.resolveArgument(methodParameter, modelAndViewContainer, webRequest, binderFactory); } catch (Exception e) { throw new IllegalStateException(e); } }
/** * 增加字符串转日期的功能 */ @PostConstruct public void initEditableValidation() { ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer) handlerAdapter.getWebBindingInitializer(); if (initializer.getConversionService() != null) { GenericConversionService genericConversionService = (GenericConversionService) initializer.getConversionService(); genericConversionService.addConverter(new StringToDateConverter()); genericConversionService.addConverter(new StringToSQLDateConverter()); } }
/** * Return the {@link ConfigurableWebBindingInitializer} to use for * initializing all {@link WebDataBinder} instances. */ protected ConfigurableWebBindingInitializer getConfigurableWebBindingInitializer() { ConfigurableWebBindingInitializer initializer = new ConfigurableWebBindingInitializer(); initializer.setConversionService(mvcConversionService()); initializer.setValidator(mvcValidator()); initializer.setMessageCodesResolver(getMessageCodesResolver()); return initializer; }
@Before public void setUp() { ConfigurableWebBindingInitializer binder = new ConfigurableWebBindingInitializer(); GenericConversionService service = new DefaultConversionService(); service.addConverter(new Converter<String, NestedBean>() { @Override public NestedBean convert(String source) { return new NestedBean(source); } }); binder.setConversionService(service); adapter.setWebBindingInitializer(binder); }
@Test @SuppressWarnings("serial") public void typeNestedSetBinding() throws Exception { servlet = new DispatcherServlet() { @Override protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) { GenericWebApplicationContext wac = new GenericWebApplicationContext(); wac.registerBeanDefinition("controller", new RootBeanDefinition(NestedSetController.class)); RootBeanDefinition csDef = new RootBeanDefinition(FormattingConversionServiceFactoryBean.class); csDef.getPropertyValues().add("converters", new TestBeanConverter()); RootBeanDefinition wbiDef = new RootBeanDefinition(ConfigurableWebBindingInitializer.class); wbiDef.getPropertyValues().add("conversionService", csDef); RootBeanDefinition adapterDef = new RootBeanDefinition(AnnotationMethodHandlerAdapter.class); adapterDef.getPropertyValues().add("webBindingInitializer", wbiDef); wac.registerBeanDefinition("handlerAdapter", adapterDef); wac.refresh(); return wac; } }; servlet.init(new MockServletConfig()); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myPath.do"); request.addParameter("testBeanSet", new String[] {"1", "2"}); MockHttpServletResponse response = new MockHttpServletResponse(); servlet.service(request, response); assertEquals("[1, 2]-org.springframework.tests.sample.beans.TestBean", response.getContentAsString()); }
@Test @SuppressWarnings("serial") public void parameterCsvAsIntegerArray() throws Exception { servlet = new DispatcherServlet() { @Override protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) { GenericWebApplicationContext wac = new GenericWebApplicationContext(); wac.registerBeanDefinition("controller", new RootBeanDefinition(CsvController.class)); RootBeanDefinition csDef = new RootBeanDefinition(FormattingConversionServiceFactoryBean.class); RootBeanDefinition wbiDef = new RootBeanDefinition(ConfigurableWebBindingInitializer.class); wbiDef.getPropertyValues().add("conversionService", csDef); RootBeanDefinition adapterDef = new RootBeanDefinition(AnnotationMethodHandlerAdapter.class); adapterDef.getPropertyValues().add("webBindingInitializer", wbiDef); wac.registerBeanDefinition("handlerAdapter", adapterDef); wac.refresh(); return wac; } }; servlet.init(new MockServletConfig()); MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI("/integerArray"); request.setMethod("POST"); request.addParameter("content", "1,2"); MockHttpServletResponse response = new MockHttpServletResponse(); servlet.service(request, response); assertEquals("1-2", response.getContentAsString()); }
@Test @SuppressWarnings("serial") public void parameterCsvAsIntegerSet() throws Exception { servlet = new DispatcherServlet() { @Override protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) { GenericWebApplicationContext wac = new GenericWebApplicationContext(); wac.registerBeanDefinition("controller", new RootBeanDefinition(CsvController.class)); RootBeanDefinition csDef = new RootBeanDefinition(FormattingConversionServiceFactoryBean.class); RootBeanDefinition wbiDef = new RootBeanDefinition(ConfigurableWebBindingInitializer.class); wbiDef.getPropertyValues().add("conversionService", csDef); RootBeanDefinition adapterDef = new RootBeanDefinition(AnnotationMethodHandlerAdapter.class); adapterDef.getPropertyValues().add("webBindingInitializer", wbiDef); wac.registerBeanDefinition("handlerAdapter", adapterDef); wac.refresh(); return wac; } }; servlet.init(new MockServletConfig()); MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI("/integerSet"); request.setMethod("POST"); request.addParameter("content", "1,2"); MockHttpServletResponse response = new MockHttpServletResponse(); servlet.service(request, response); assertEquals("1-2", response.getContentAsString()); }
@Test @SuppressWarnings("serial") public void parameterCsvAsIntegerSetWithCustomSeparator() throws Exception { servlet = new DispatcherServlet() { @Override protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) { GenericWebApplicationContext wac = new GenericWebApplicationContext(); wac.registerBeanDefinition("controller", new RootBeanDefinition(CsvController.class)); RootBeanDefinition csDef = new RootBeanDefinition(FormattingConversionServiceFactoryBean.class); RootBeanDefinition wbiDef = new RootBeanDefinition(ConfigurableWebBindingInitializer.class); wbiDef.getPropertyValues().add("conversionService", csDef); wbiDef.getPropertyValues().add("propertyEditorRegistrars", new RootBeanDefinition(ListEditorRegistrar.class)); RootBeanDefinition adapterDef = new RootBeanDefinition(AnnotationMethodHandlerAdapter.class); adapterDef.getPropertyValues().add("webBindingInitializer", wbiDef); wac.registerBeanDefinition("handlerAdapter", adapterDef); wac.refresh(); return wac; } }; servlet.init(new MockServletConfig()); MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI("/integerSet"); request.setMethod("POST"); request.addParameter("content", "1;2"); MockHttpServletResponse response = new MockHttpServletResponse(); servlet.service(request, response); assertEquals("1-2", response.getContentAsString()); }
@Test public void webBindingInitializer() throws Exception { RequestMappingHandlerAdapter adapter = this.config.requestMappingHandlerAdapter(); ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer) adapter.getWebBindingInitializer(); assertNotNull(initializer); BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(null, ""); initializer.getValidator().validate(null, bindingResult); assertEquals("invalid", bindingResult.getAllErrors().get(0).getCode()); String[] codes = initializer.getMessageCodesResolver().resolveMessageCodes("invalid", null); assertEquals("custom.invalid", codes[0]); }
@Test public void requestMappingHandlerAdapter() throws Exception { ApplicationContext context = initContext(WebConfig.class); RequestMappingHandlerAdapter adapter = context.getBean(RequestMappingHandlerAdapter.class); List<HttpMessageConverter<?>> converters = adapter.getMessageConverters(); assertEquals(9, converters.size()); for(HttpMessageConverter<?> converter : converters) { if (converter instanceof AbstractJackson2HttpMessageConverter) { ObjectMapper objectMapper = ((AbstractJackson2HttpMessageConverter)converter).getObjectMapper(); assertFalse(objectMapper.getDeserializationConfig().isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)); assertFalse(objectMapper.getSerializationConfig().isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)); assertFalse(objectMapper.getDeserializationConfig().isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)); if (converter instanceof MappingJackson2XmlHttpMessageConverter) { assertEquals(XmlMapper.class, objectMapper.getClass()); } } } ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer) adapter.getWebBindingInitializer(); assertNotNull(initializer); ConversionService conversionService = initializer.getConversionService(); assertNotNull(conversionService); assertTrue(conversionService instanceof FormattingConversionService); Validator validator = initializer.getValidator(); assertNotNull(validator); assertTrue(validator instanceof LocalValidatorFactoryBean); DirectFieldAccessor fieldAccessor = new DirectFieldAccessor(adapter); @SuppressWarnings("unchecked") List<Object> bodyAdvice = (List<Object>) fieldAccessor.getPropertyValue("requestResponseBodyAdvice"); assertEquals(2, bodyAdvice.size()); assertEquals(JsonViewRequestBodyAdvice.class, bodyAdvice.get(0).getClass()); assertEquals(JsonViewResponseBodyAdvice.class, bodyAdvice.get(1).getClass()); }
@Test public void testMessageCodesResolver() { loadBeanDefinitions("mvc-config-message-codes-resolver.xml"); RequestMappingHandlerAdapter adapter = appContext.getBean(RequestMappingHandlerAdapter.class); assertNotNull(adapter); Object initializer = adapter.getWebBindingInitializer(); assertNotNull(initializer); MessageCodesResolver resolver = ((ConfigurableWebBindingInitializer) initializer).getMessageCodesResolver(); assertNotNull(resolver); assertEquals(TestMessageCodesResolver.class, resolver.getClass()); assertEquals(false, new DirectFieldAccessor(adapter).getPropertyValue("ignoreDefaultModelOnRedirect")); }
@Override @SuppressWarnings("unchecked") public <T> T provide(Method method, int parameterIndex) { MethodParameter methodParameter = new MethodParameter(method, parameterIndex); ModelAndViewContainer modelAndViewContainer = new ModelAndViewContainer(); NativeWebRequest webRequest = new ServletWebRequest(request); DefaultDataBinderFactory binderFactory = new DefaultDataBinderFactory(new ConfigurableWebBindingInitializer()); try { return (T) argumentResolvers.resolveArgument(methodParameter, modelAndViewContainer, webRequest, binderFactory); } catch (Exception e) { throw new RuntimeException(e); } }
@Override protected ConfigurableWebBindingInitializer getConfigurableWebBindingInitializer() { try { return this.beanFactory.getBean(ConfigurableWebBindingInitializer.class); } catch (NoSuchBeanDefinitionException ex) { return super.getConfigurableWebBindingInitializer(); } }
@Test public void webBindingInitializer() throws Exception { RequestMappingHandlerAdapter adapter = webConfig.requestMappingHandlerAdapter(); ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer) adapter.getWebBindingInitializer(); assertNotNull(initializer); BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(null, ""); initializer.getValidator().validate(null, bindingResult); assertEquals("invalid", bindingResult.getAllErrors().get(0).getCode()); String[] codes = initializer.getMessageCodesResolver().resolveMessageCodes("invalid", null); assertEquals("custom.invalid", codes[0]); }
@Before public void setUp() throws Exception { MockServletContext sc = new MockServletContext(); request = new MockHttpServletRequest(sc); webRequest = new ServletWebRequest(request); RequestContextHolder.setRequestAttributes(webRequest); request.setAttribute(DispatcherServlet.OUTPUT_FLASH_MAP_ATTRIBUTE, new FlashMap()); factory = new DefaultDataBinderFactory(new ConfigurableWebBindingInitializer()); }
@Before public void setUp() throws Exception { bindingInitializer = new ConfigurableWebBindingInitializer(); argumentResolvers = new HandlerMethodArgumentResolverComposite(); webRequest = new ServletWebRequest(new MockHttpServletRequest()); }