Java Code Examples for org.springframework.web.servlet.DispatcherServlet#init()

The following examples show how to use org.springframework.web.servlet.DispatcherServlet#init() . 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: CglibProxyControllerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@SuppressWarnings("serial")
private void initServlet(final Class<?> controllerClass) throws ServletException {
	servlet = new DispatcherServlet() {
		@Override
		protected WebApplicationContext createWebApplicationContext(@Nullable WebApplicationContext parent) {
			GenericWebApplicationContext wac = new GenericWebApplicationContext();
			wac.registerBeanDefinition("controller", new RootBeanDefinition(controllerClass));
			DefaultAdvisorAutoProxyCreator autoProxyCreator = new DefaultAdvisorAutoProxyCreator();
			autoProxyCreator.setProxyTargetClass(true);
			autoProxyCreator.setBeanFactory(wac.getBeanFactory());
			wac.getBeanFactory().addBeanPostProcessor(autoProxyCreator);
			Pointcut pointcut = new AnnotationMatchingPointcut(Controller.class);
			DefaultPointcutAdvisor advisor = new DefaultPointcutAdvisor(pointcut, new SimpleTraceInterceptor(true));
			wac.getBeanFactory().registerSingleton("advisor", advisor);
			wac.refresh();
			return wac;
		}
	};
	servlet.init(new MockServletConfig());
}
 
Example 2
Source File: ServletAnnotationControllerTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void modelFormController() throws Exception {
	@SuppressWarnings("serial") DispatcherServlet servlet = new DispatcherServlet() {
		@Override
		protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) {
			GenericWebApplicationContext wac = new GenericWebApplicationContext();
			wac.registerBeanDefinition("controller", new RootBeanDefinition(MyModelFormController.class));
			wac.registerBeanDefinition("viewResolver", new RootBeanDefinition(TestViewResolver.class));
			wac.refresh();
			return wac;
		}
	};
	servlet.init(new MockServletConfig());

	MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myPath.do");
	request.addParameter("name", "name1");
	request.addParameter("age", "value2");
	MockHttpServletResponse response = new MockHttpServletResponse();
	servlet.service(request, response);
	assertEquals("myPath-name1-typeMismatch-tb1-myValue-yourValue", response.getContentAsString());
}
 
Example 3
Source File: ResponseEntityExceptionHandlerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void controllerAdviceWithNestedExceptionWithinDispatcherServlet() throws Exception {
	StaticWebApplicationContext ctx = new StaticWebApplicationContext();
	ctx.registerSingleton("controller", NestedExceptionThrowingController.class);
	ctx.registerSingleton("exceptionHandler", ApplicationExceptionHandler.class);
	ctx.refresh();

	DispatcherServlet servlet = new DispatcherServlet(ctx);
	servlet.init(new MockServletConfig());
	try {
		servlet.service(this.servletRequest, this.servletResponse);
	}
	catch (ServletException ex) {
		assertTrue(ex.getCause() instanceof IllegalStateException);
		assertTrue(ex.getCause().getCause() instanceof ServletRequestBindingException);
	}
}
 
Example 4
Source File: UriTemplateServletAnnotationControllerTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("serial")
public void noDefaultSuffixPattern() throws Exception {
	servlet = new DispatcherServlet() {
		@Override
		protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent)
				throws BeansException {
			GenericWebApplicationContext wac = new GenericWebApplicationContext();
			wac.registerBeanDefinition("controller", new RootBeanDefinition(ImplicitSubPathController.class));
			RootBeanDefinition mappingDef = new RootBeanDefinition(DefaultAnnotationHandlerMapping.class);
			mappingDef.getPropertyValues().add("useDefaultSuffixPattern", false);
			wac.registerBeanDefinition("handlerMapping", mappingDef);
			wac.refresh();
			return wac;
		}
	};
	servlet.init(new MockServletConfig());

	MockHttpServletRequest request = new MockHttpServletRequest("GET", "/hotels/hotel.with.dot");
	MockHttpServletResponse response = new MockHttpServletResponse();
	servlet.service(request, response);
	assertEquals("test-hotel.with.dot", response.getContentAsString());
}
 
Example 5
Source File: SpringWebMvc_5_x_IT.java    From pinpoint with Apache License 2.0 6 votes vote down vote up
@Test
public void testRequest() throws Exception {
    MockServletConfig config = new MockServletConfig();
    MockHttpServletRequest req = new MockHttpServletRequest();
    MockHttpServletResponse res = new MockHttpServletResponse();

    config.addInitParameter("contextConfigLocation", "classpath:spring-web-test.xml");
    req.setMethod("GET");
    req.setRequestURI("/");
    req.setRemoteAddr("1.2.3.4");
    
    DispatcherServlet servlet = new DispatcherServlet();
    servlet.init(config);
    
    servlet.service(req, res);
    
    Method method = FrameworkServlet.class.getDeclaredMethod("doGet", HttpServletRequest.class, HttpServletResponse.class);
    
    PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
    verifier.printCache();
    
    verifier.verifyTrace(Expectations.event(SPRING_MVC, method));
    verifier.verifyTraceCount(0);
}
 
Example 6
Source File: ServletAnnotationControllerTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("serial")
public void emptyValueMapping() throws Exception {
	servlet = new DispatcherServlet() {
		@Override
		protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) {
			GenericWebApplicationContext wac = new GenericWebApplicationContext();
			wac.registerBeanDefinition("controller", new RootBeanDefinition(ControllerWithEmptyValueMapping.class));
			wac.refresh();
			return wac;
		}
	};
	servlet.init(new MockServletConfig());

	MockHttpServletRequest request = new MockHttpServletRequest("GET", "/foo");
	request.setContextPath("/foo");
	request.setServletPath("");
	MockHttpServletResponse response = new MockHttpServletResponse();
	servlet.service(request, response);
	assertEquals("test", response.getContentAsString());
}
 
Example 7
Source File: AnnotationConfigDispatcherServletInitializerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void rootContextOnly() throws ServletException {
	initializer = new MyAnnotationConfigDispatcherServletInitializer() {
		@Override
		protected Class<?>[] getRootConfigClasses() {
			return new Class<?>[] {MyConfiguration.class};
		}
		@Override
		protected Class<?>[] getServletConfigClasses() {
			return null;
		}
	};

	initializer.onStartup(servletContext);

	DispatcherServlet servlet = (DispatcherServlet) servlets.get(SERVLET_NAME);
	servlet.init(new MockServletConfig(this.servletContext));

	WebApplicationContext wac = servlet.getWebApplicationContext();
	((AnnotationConfigWebApplicationContext) wac).refresh();

	assertTrue(wac.containsBean("bean"));
	assertTrue(wac.getBean("bean") instanceof MyBean);
}
 
Example 8
Source File: ResponseEntityExceptionHandlerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void controllerAdviceWithNestedExceptionWithinDispatcherServlet() throws Exception {
	StaticWebApplicationContext ctx = new StaticWebApplicationContext();
	ctx.registerSingleton("controller", NestedExceptionThrowingController.class);
	ctx.registerSingleton("exceptionHandler", ApplicationExceptionHandler.class);
	ctx.refresh();

	DispatcherServlet servlet = new DispatcherServlet(ctx);
	servlet.init(new MockServletConfig());
	try {
		servlet.service(this.servletRequest, this.servletResponse);
	}
	catch (ServletException ex) {
		assertTrue(ex.getCause() instanceof IllegalStateException);
		assertTrue(ex.getCause().getCause() instanceof ServletRequestBindingException);
	}
}
 
Example 9
Source File: ServletAnnotationControllerTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example 10
Source File: ContextLoaderTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testFrameworkServletWithCustomLocation() throws Exception {
	DispatcherServlet servlet = new DispatcherServlet();
	servlet.setContextConfigLocation("/org/springframework/web/context/WEB-INF/testNamespace.xml "
			+ "/org/springframework/web/context/WEB-INF/context-addition.xml");
	servlet.init(new MockServletConfig(new MockServletContext(""), "test"));
	assertTrue(servlet.getWebApplicationContext().containsBean("kerry"));
	assertTrue(servlet.getWebApplicationContext().containsBean("kerryX"));
}
 
Example 11
Source File: ContextLoaderTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testFrameworkServletWithCustomLocation() throws Exception {
	DispatcherServlet servlet = new DispatcherServlet();
	servlet.setContextConfigLocation("/org/springframework/web/context/WEB-INF/testNamespace.xml "
			+ "/org/springframework/web/context/WEB-INF/context-addition.xml");
	servlet.init(new MockServletConfig(new MockServletContext(""), "test"));
	assertTrue(servlet.getWebApplicationContext().containsBean("kerry"));
	assertTrue(servlet.getWebApplicationContext().containsBean("kerryX"));
}
 
Example 12
Source File: ContextLoaderTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testFrameworkServletWithDefaultLocation() throws Exception {
	DispatcherServlet servlet = new DispatcherServlet();
	servlet.setContextClass(XmlWebApplicationContext.class);
	try {
		servlet.init(new MockServletConfig(new MockServletContext(""), "test"));
		fail("Should have thrown BeanDefinitionStoreException");
	}
	catch (BeanDefinitionStoreException ex) {
		// expected
		assertTrue(ex.getCause() instanceof IOException);
		assertTrue(ex.getCause().getMessage().contains("/WEB-INF/test-servlet.xml"));
	}
}
 
Example 13
Source File: ServletAnnotationControllerTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example 14
Source File: ResponseEntityExceptionHandlerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void controllerAdviceWithinDispatcherServlet() throws Exception {
	StaticWebApplicationContext ctx = new StaticWebApplicationContext();
	ctx.registerSingleton("controller", ExceptionThrowingController.class);
	ctx.registerSingleton("exceptionHandler", ApplicationExceptionHandler.class);
	ctx.refresh();

	DispatcherServlet servlet = new DispatcherServlet(ctx);
	servlet.init(new MockServletConfig());
	servlet.service(this.servletRequest, this.servletResponse);

	assertEquals(400, this.servletResponse.getStatus());
	assertEquals("error content", this.servletResponse.getContentAsString());
	assertEquals("someHeaderValue", this.servletResponse.getHeader("someHeader"));
}
 
Example 15
Source File: ServletAnnotationControllerTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void responseBodyNoAcceptableMediaType() throws ServletException, IOException {
	@SuppressWarnings("serial") DispatcherServlet servlet = new DispatcherServlet() {
		@Override
		protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) {
			GenericWebApplicationContext wac = new GenericWebApplicationContext();
			wac.registerBeanDefinition("controller", new RootBeanDefinition(RequestResponseBodyController.class));
			RootBeanDefinition converterDef = new RootBeanDefinition(StringHttpMessageConverter.class);
			converterDef.getPropertyValues().add("supportedMediaTypes", new MediaType("text", "plain"));
			RootBeanDefinition adapterDef = new RootBeanDefinition(AnnotationMethodHandlerAdapter.class);
			StringHttpMessageConverter converter = new StringHttpMessageConverter();
			converter.setSupportedMediaTypes(Collections.singletonList(new MediaType("text", "plain")));
			adapterDef.getPropertyValues().add("messageConverters", converter);
			wac.registerBeanDefinition("handlerAdapter", adapterDef);
			wac.refresh();
			return wac;
		}
	};
	servlet.init(new MockServletConfig());

	MockHttpServletRequest request = new MockHttpServletRequest("PUT", "/something");
	String requestBody = "Hello World";
	request.setContent(requestBody.getBytes("UTF-8"));
	request.addHeader("Content-Type", "text/plain; charset=utf-8");
	request.addHeader("Accept", "application/pdf, application/msword");
	MockHttpServletResponse response = new MockHttpServletResponse();
	servlet.service(request, response);
	assertEquals(406, response.getStatus());
}
 
Example 16
Source File: ServletAnnotationControllerTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example 17
Source File: ContextLoaderTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void testFrameworkServletWithCustomLocation() throws Exception {
	DispatcherServlet servlet = new DispatcherServlet();
	servlet.setContextConfigLocation("/org/springframework/web/context/WEB-INF/testNamespace.xml "
			+ "/org/springframework/web/context/WEB-INF/context-addition.xml");
	servlet.init(new MockServletConfig(new MockServletContext(""), "test"));
	assertTrue(servlet.getWebApplicationContext().containsBean("kerry"));
	assertTrue(servlet.getWebApplicationContext().containsBean("kerryX"));
}
 
Example 18
Source File: ServletAnnotationControllerTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("serial")
public void defaultExpressionParameters() throws Exception {
	servlet = new DispatcherServlet() {
		@Override
		protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) {
			GenericWebApplicationContext wac = new GenericWebApplicationContext();
			wac.registerBeanDefinition("controller", new RootBeanDefinition(DefaultExpressionValueParamController.class));
			RootBeanDefinition ppc = new RootBeanDefinition(PropertyPlaceholderConfigurer.class);
			ppc.getPropertyValues().add("properties", "myKey=foo");
			wac.registerBeanDefinition("ppc", ppc);
			wac.refresh();
			return wac;
		}
	};
	servlet.init(new MockServletConfig());

	MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myApp/myPath.do");
	request.setContextPath("/myApp");
	MockHttpServletResponse response = new MockHttpServletResponse();
	System.setProperty("myHeader", "bar");
	try {
		servlet.service(request, response);
	}
	finally {
		System.clearProperty("myHeader");
	}
	assertEquals("foo-bar-/myApp", response.getContentAsString());
}
 
Example 19
Source File: UriTemplateServletAnnotationControllerTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("serial")
private void initServlet(final Class<?> controllerclass) throws ServletException {
	servlet = new DispatcherServlet() {
		@Override
		protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent)
				throws BeansException {
			GenericWebApplicationContext wac = new GenericWebApplicationContext();
			wac.registerBeanDefinition("controller", new RootBeanDefinition(controllerclass));
			wac.refresh();
			return wac;
		}
	};
	servlet.init(new MockServletConfig());
}
 
Example 20
Source File: AbstractServletHandlerMethodTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Initialize a DispatcherServlet instance registering zero or more controller classes
 * and also providing additional bean definitions through a callback.
 */
@SuppressWarnings("serial")
protected WebApplicationContext initServlet(
		final ApplicationContextInitializer<GenericWebApplicationContext> initializer,
		final Class<?>... controllerClasses) throws ServletException {

	final GenericWebApplicationContext wac = new GenericWebApplicationContext();

	servlet = new DispatcherServlet() {
		@Override
		protected WebApplicationContext createWebApplicationContext(@Nullable WebApplicationContext parent) {
			for (Class<?> clazz : controllerClasses) {
				wac.registerBeanDefinition(clazz.getSimpleName(), new RootBeanDefinition(clazz));
			}

			RootBeanDefinition mappingDef = new RootBeanDefinition(RequestMappingHandlerMapping.class);
			mappingDef.getPropertyValues().add("removeSemicolonContent", "false");
			wac.registerBeanDefinition("handlerMapping", mappingDef);
			wac.registerBeanDefinition("handlerAdapter",
					new RootBeanDefinition(RequestMappingHandlerAdapter.class));
			wac.registerBeanDefinition("requestMappingResolver",
					new RootBeanDefinition(ExceptionHandlerExceptionResolver.class));
			wac.registerBeanDefinition("responseStatusResolver",
					new RootBeanDefinition(ResponseStatusExceptionResolver.class));
			wac.registerBeanDefinition("defaultResolver",
					new RootBeanDefinition(DefaultHandlerExceptionResolver.class));

			if (initializer != null) {
				initializer.initialize(wac);
			}

			wac.refresh();
			return wac;
		}
	};

	servlet.init(new MockServletConfig());

	return wac;
}