Java Code Examples for org.springframework.web.servlet.DispatcherServlet

The following examples show how to use org.springframework.web.servlet.DispatcherServlet. These examples are extracted from open source projects. 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 Project: spring4-understanding   Source File: RedirectViewTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void updateTargetUrl() throws Exception {
	StaticWebApplicationContext wac = new StaticWebApplicationContext();
	wac.registerSingleton("requestDataValueProcessor", RequestDataValueProcessorWrapper.class);
	wac.setServletContext(new MockServletContext());
	wac.refresh();

	RequestDataValueProcessor mockProcessor = mock(RequestDataValueProcessor.class);
	wac.getBean(RequestDataValueProcessorWrapper.class).setRequestDataValueProcessor(mockProcessor);

	RedirectView rv = new RedirectView();
	rv.setApplicationContext(wac);	// Init RedirectView with WebAppCxt
	rv.setUrl("/path");

	MockHttpServletRequest request = createRequest();
	request.setAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
	HttpServletResponse response = new MockHttpServletResponse();

	given(mockProcessor.processUrl(request, "/path")).willReturn("/path?key=123");

	rv.render(new ModelMap(), request, response);

	verify(mockProcessor).processUrl(request, "/path");
}
 
Example 2
@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 3
@Test
@SuppressWarnings("serial")
public void suppressDefaultSuffixPattern() throws Exception {
	servlet = new DispatcherServlet() {
		@Override
		protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent)
				throws BeansException {
			GenericWebApplicationContext wac = new GenericWebApplicationContext();
			wac.registerBeanDefinition("controller", new RootBeanDefinition(VariableNamesController.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", "/test/[email protected]");
	MockHttpServletResponse response = new MockHttpServletResponse();
	servlet.service(request, response);
	assertEquals("[email protected]", response.getContentAsString());
}
 
Example 4
Source Project: layui-admin   Source File: LayuiAdminStartUp.java    License: MIT License 6 votes vote down vote up
@Bean
public ServletWebServerFactory servletContainer() {
    TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();
    tomcat.addInitializers(new ServletContextInitializer(){
        @Override
        public void onStartup(ServletContext servletContext) throws ServletException {
            XmlWebApplicationContext context = new XmlWebApplicationContext();
            context.setConfigLocations(new String[]{"classpath:applicationContext-springmvc.xml"});
            DispatcherServlet dispatcherServlet = new DispatcherServlet(context);
            ServletRegistration.Dynamic dispatcher = servletContext
                    .addServlet("dispatcher", dispatcherServlet);

            dispatcher.setLoadOnStartup(1);
            dispatcher.addMapping("/");
        }
    });
    tomcat.setContextPath("/manager");
    tomcat.addTldSkipPatterns("xercesImpl.jar","xml-apis.jar","serializer.jar");
    tomcat.setPort(port);

    return tomcat;
}
 
Example 5
@Test
public void binderInitializingCommandProvidingFormController() throws Exception {
	@SuppressWarnings("serial") DispatcherServlet servlet = new DispatcherServlet() {
		@Override
		protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) {
			GenericWebApplicationContext wac = new GenericWebApplicationContext();
			wac.registerBeanDefinition("controller",
					new RootBeanDefinition(MyBinderInitializingCommandProvidingFormController.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("defaultName", "myDefaultName");
	request.addParameter("age", "value2");
	request.addParameter("date", "2007-10-02");
	MockHttpServletResponse response = new MockHttpServletResponse();
	servlet.service(request, response);
	assertEquals("myView-String:myDefaultName-typeMismatch-tb1-myOriginalValue", response.getContentAsString());
}
 
Example 6
Source Project: Spring-5.0-Cookbook   Source File: SpringWebInitializer.java    License: MIT License 6 votes vote down vote up
private void addDispatcherContext(ServletContext container) {
	// Create the dispatcher servlet's Spring application context
	AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();
	dispatcherContext.register(SpringDispatcherConfig.class);

	// Declare <servlet> and <servlet-mapping> for the DispatcherServlet
	ServletRegistration.Dynamic dispatcher = container.addServlet("ch03-servlet",
			new DispatcherServlet(dispatcherContext));
	dispatcher.addMapping("*.html");
	dispatcher.setLoadOnStartup(1);

	FilterRegistration.Dynamic corsFilter = container.addFilter("corsFilter", new CorsFilter());
	corsFilter.setInitParameter("cors.allowed.methods", "GET, POST, HEAD, OPTIONS, PUT, DELETE");
	corsFilter.addMappingForUrlPatterns(null, true, "/*");

	FilterRegistration.Dynamic filter = container.addFilter("hiddenmethodfilter", new HiddenHttpMethodFilter());
	filter.addMappingForServletNames(null, true, "/*");

	FilterRegistration.Dynamic multipartFilter = container.addFilter("multipartFilter", new MultipartFilter());
	multipartFilter.addMappingForUrlPatterns(null, true, "/*");

}
 
Example 7
@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
@Override
public void initialize(AnnotationConfigWebApplicationContext applicationContext) {
	final AnnotationConfigWebApplicationContext rootCtx = new AnnotationConfigWebApplicationContext();
	rootCtx.register(TraceeInterceptorSpringConfig.class);
	final ServletContext servletContext = applicationContext.getServletContext();

	// Manage the lifecycle of the root application context
	servletContext.addListener(new ContextLoaderListener(rootCtx));

	// Create the dispatcher servlet's Spring application context
	AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();
	dispatcherContext.register(TraceeInterceptorSpringConfig.class);

	// Register and map the dispatcher servlet
	ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", new DispatcherServlet(dispatcherContext));
	dispatcher.setLoadOnStartup(1);
	dispatcher.addMapping("/");

}
 
Example 9
Source Project: tutorials   Source File: MainWebAppInitializer.java    License: MIT License 6 votes vote down vote up
@Override
public void onStartup(final ServletContext sc) throws ServletException {

    // Create the 'root' Spring application context
    final AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext();
    root.register(WebConfig.class);

    // Manages the lifecycle of the root application context
    sc.addListener(new ContextLoaderListener(root));

    // Handles requests into the application
    final ServletRegistration.Dynamic appServlet = sc.addServlet("mvc", new DispatcherServlet(new GenericWebApplicationContext()));
    appServlet.setLoadOnStartup(1);

    final Set<String> mappingConflicts = appServlet.addMapping("/");
    if (!mappingConflicts.isEmpty()) {
        throw new IllegalStateException("'appServlet' could not be mapped to '/' due " + "to an existing mapping. This is a known issue under Tomcat versions " + "<= 7.0.14; see https://issues.apache.org/bugzilla/show_bug.cgi?id=51278");
    }
}
 
Example 10
Source Project: sakai   Source File: WebAppConfiguration.java    License: Educational Community License v2.0 6 votes vote down vote up
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
    AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
    rootContext.setServletContext(servletContext);
    rootContext.register(ThymeleafConfig.class);

    servletContext.addListener(new ToolListener());
    servletContext.addListener(new SakaiContextLoaderListener(rootContext));
    
    FilterRegistration requestFilterRegistration = servletContext.addFilter("sakai.request", RequestFilter.class);
    requestFilterRegistration.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.INCLUDE), true, "/*");
    requestFilterRegistration.setInitParameter(RequestFilter.CONFIG_UPLOAD_ENABLED, "true");       

    Dynamic servlet = servletContext.addServlet("sakai-site-group-manager", new DispatcherServlet(rootContext));
    servlet.addMapping("/");
    servlet.setLoadOnStartup(1);
}
 
Example 11
@Test
@SuppressWarnings("serial")
public void doubles() throws Exception {
	servlet = new DispatcherServlet() {
		@Override
		protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent)
				throws BeansException {
			GenericWebApplicationContext wac = new GenericWebApplicationContext();
			wac.registerBeanDefinition("controller", new RootBeanDefinition(DoubleController.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", "/lat/1.2/long/3.4");
	MockHttpServletResponse response = new MockHttpServletResponse();
	servlet.service(request, response);

	assertEquals("latitude-1.2-longitude-3.4", response.getContentAsString());
}
 
Example 12
Source Project: java-technology-stack   Source File: AbstractTagTests.java    License: MIT License 6 votes vote down vote up
protected MockPageContext createPageContext() {
	MockServletContext sc = new MockServletContext();
	SimpleWebApplicationContext wac = new SimpleWebApplicationContext();
	wac.setServletContext(sc);
	wac.setNamespace("test");
	wac.refresh();

	MockHttpServletRequest request = new MockHttpServletRequest(sc);
	MockHttpServletResponse response = new MockHttpServletResponse();
	if (inDispatcherServlet()) {
		request.setAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
		LocaleResolver lr = new AcceptHeaderLocaleResolver();
		request.setAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE, lr);
		ThemeResolver tr = new FixedThemeResolver();
		request.setAttribute(DispatcherServlet.THEME_RESOLVER_ATTRIBUTE, tr);
		request.setAttribute(DispatcherServlet.THEME_SOURCE_ATTRIBUTE, wac);
	}
	else {
		sc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
	}

	return new MockPageContext(sc, request, response);
}
 
Example 13
Source Project: java-technology-stack   Source File: JdkProxyControllerTests.java    License: 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.setBeanFactory(wac.getBeanFactory());
			wac.getBeanFactory().addBeanPostProcessor(autoProxyCreator);
			wac.getBeanFactory().registerSingleton("advisor", new DefaultPointcutAdvisor(new SimpleTraceInterceptor(true)));
			wac.refresh();
			return wac;
		}
	};
	servlet.init(new MockServletConfig());
}
 
Example 14
Source Project: sakai   Source File: WebAppConfiguration.java    License: Educational Community License v2.0 6 votes vote down vote up
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
    AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
    rootContext.setServletContext(servletContext);
    rootContext.register(ThymeleafConfig.class);

    servletContext.addListener(new ToolListener());
    servletContext.addListener(new SakaiContextLoaderListener(rootContext));

    servletContext.addFilter("sakai.request", RequestFilter.class)
            .addMappingForUrlPatterns(
                    EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.INCLUDE),
                    true,
                    "/*");

    Dynamic servlet = servletContext.addServlet("sakai.message.bundle.manager", new DispatcherServlet(rootContext));
    servlet.addMapping("/");
    servlet.setLoadOnStartup(1);
}
 
Example 15
Source Project: flowable-engine   Source File: WebConfigurer.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Initializes Spring and Spring MVC.
 */
private ServletRegistration.Dynamic initSpring(ServletContext servletContext, AnnotationConfigWebApplicationContext rootContext) {
    LOGGER.debug("Configuring Spring Web application context");
    AnnotationConfigWebApplicationContext dispatcherServletConfiguration = new AnnotationConfigWebApplicationContext();
    dispatcherServletConfiguration.setParent(rootContext);
    dispatcherServletConfiguration.register(DispatcherServletConfiguration.class);

    LOGGER.debug("Registering Spring MVC Servlet");
    ServletRegistration.Dynamic dispatcherServlet = servletContext.addServlet("dispatcher", new DispatcherServlet(dispatcherServletConfiguration));
    dispatcherServlet.addMapping("/service/*");
    dispatcherServlet.setMultipartConfig(new MultipartConfigElement((String) null));
    dispatcherServlet.setLoadOnStartup(1);
    dispatcherServlet.setAsyncSupported(true);

    return dispatcherServlet;
}
 
Example 16
@Test
@SuppressWarnings("serial")
public void proxiedStandardHandleMethod() throws Exception {
	DispatcherServlet servlet = new DispatcherServlet() {
		@Override
		protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) {
			GenericWebApplicationContext wac = new GenericWebApplicationContext();
			wac.registerBeanDefinition("controller", new RootBeanDefinition(MyController.class));
			DefaultAdvisorAutoProxyCreator autoProxyCreator = new DefaultAdvisorAutoProxyCreator();
			autoProxyCreator.setBeanFactory(wac.getBeanFactory());
			wac.getBeanFactory().addBeanPostProcessor(autoProxyCreator);
			wac.getBeanFactory().registerSingleton("advisor", new DefaultPointcutAdvisor(new SimpleTraceInterceptor()));
			wac.refresh();
			return wac;
		}
	};
	servlet.init(new MockServletConfig());

	MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myPath.do");
	MockHttpServletResponse response = new MockHttpServletResponse();
	servlet.service(request, response);
	assertEquals("test", response.getContentAsString());
}
 
Example 17
@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 18
Source Project: herd   Source File: WarInitializer.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Initializes the dispatch servlet which is used for Spring MVC REST and UI controllers.
 *
 * @param servletContext the servlet context.
 */
protected void initDispatchServlet(ServletContext servletContext)
{
    // Add the dispatch servlet to handle user URL's and REST URL's.
    AnnotationConfigWebApplicationContext dispatchServletContext = new AnnotationConfigWebApplicationContext();
    ServletRegistration.Dynamic servlet = servletContext.addServlet("springMvcServlet", new DispatcherServlet(dispatchServletContext));
    servlet.addMapping("/");
    servlet.setLoadOnStartup(1);
}
 
Example 19
Source Project: spring4-understanding   Source File: UndertowTestServer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public InstanceHandle<Servlet> createInstance() throws InstantiationException {
	return new InstanceHandle<Servlet>() {
		@Override
		public Servlet getInstance() {
			return new DispatcherServlet(wac);
		}
		@Override
		public void release() {
		}
	};
}
 
Example 20
@Test
public void handleRequestWithFlashAttributes() throws Exception {
	this.request.setAttribute(DispatcherServlet.INPUT_FLASH_MAP_ATTRIBUTE, new ModelMap("name", "value"));
	ModelAndView mav = this.controller.handleRequest(this.request, new MockHttpServletResponse());
	assertEquals(1, mav.getModel().size());
	assertEquals("value", mav.getModel().get("name"));
}
 
Example 21
Source Project: spring4-understanding   Source File: ViewResolverTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testInternalResourceViewResolverWithContextBeans() throws Exception {
	MockServletContext sc = new MockServletContext();
	final StaticWebApplicationContext wac = new StaticWebApplicationContext();
	wac.registerSingleton("myBean", TestBean.class);
	wac.registerSingleton("myBean2", TestBean.class);
	wac.setServletContext(sc);
	wac.refresh();
	InternalResourceViewResolver vr = new InternalResourceViewResolver();
	Properties props = new Properties();
	props.setProperty("key1", "value1");
	vr.setAttributes(props);
	Map map = new HashMap();
	map.put("key2", new Integer(2));
	vr.setAttributesMap(map);
	vr.setExposeContextBeansAsAttributes(true);
	vr.setApplicationContext(wac);

	MockHttpServletRequest request = new MockHttpServletRequest(sc) {
		@Override
		public RequestDispatcher getRequestDispatcher(String path) {
			return new MockRequestDispatcher(path) {
				@Override
				public void forward(ServletRequest forwardRequest, ServletResponse forwardResponse) {
					assertTrue("Correct rc attribute", forwardRequest.getAttribute("rc") == null);
					assertEquals("value1", forwardRequest.getAttribute("key1"));
					assertEquals(new Integer(2), forwardRequest.getAttribute("key2"));
					assertSame(wac.getBean("myBean"), forwardRequest.getAttribute("myBean"));
					assertSame(wac.getBean("myBean2"), forwardRequest.getAttribute("myBean2"));
				}
			};
		}
	};
	HttpServletResponse response = new MockHttpServletResponse();
	request.setAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
	request.setAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE, new AcceptHeaderLocaleResolver());
	View view = vr.resolveViewName("example1", Locale.getDefault());
	view.render(new HashMap(), request, response);
}
 
Example 22
Source Project: wingtips   Source File: Main.java    License: Apache License 2.0 5 votes vote down vote up
private static ServletContextHandler generateServletContextHandler(
    WebApplicationContext webappContext
) throws IOException {
    ServletContextHandler contextHandler = new ServletContextHandler();
    contextHandler.setContextPath("/");
    contextHandler.addServlet(new ServletHolder(new DispatcherServlet(webappContext)), "/*");
    contextHandler.addEventListener(new ContextLoaderListener(webappContext));
    FilterHolder requestTracingFilterHolder = contextHandler.addFilter(
        RequestTracingFilter.class, "/*", EnumSet.allOf(DispatcherType.class)
    );
    requestTracingFilterHolder.setInitParameter(USER_ID_HEADER_KEYS_LIST_INIT_PARAM_NAME, USER_ID_HEADER_KEYS);
    return contextHandler;
}
 
Example 23
Source Project: spring-soy-view   Source File: SpringLocaleProvider.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Optional<Locale> resolveLocale(final HttpServletRequest request) {
    final LocaleResolver localeResolver = (LocaleResolver) request.getAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE);
    if (localeResolver != null) {
        final Locale locale = localeResolver.resolveLocale(request);
        if (locale != null) {
            return Optional.of(locale);
        }
    }

    return Optional.fromNullable(request.getLocale());
}
 
Example 24
@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());
}
 
Example 25
@Test
public void withFlashAttributes() throws Exception {
	UrlFilenameViewController ctrl = new UrlFilenameViewController();
	MockHttpServletRequest request = new MockHttpServletRequest("GET", "/index");
	request.setAttribute(DispatcherServlet.INPUT_FLASH_MAP_ATTRIBUTE, new ModelMap("name", "value"));
	MockHttpServletResponse response = new MockHttpServletResponse();
	ModelAndView mv = ctrl.handleRequest(request, response);
	assertEquals("index", mv.getViewName());
	assertEquals(1, mv.getModel().size());
	assertEquals("value", mv.getModel().get("name"));
}
 
Example 26
Source Project: Spring-5.0-Cookbook   Source File: SpringWebinitializer.java    License: MIT License 5 votes vote down vote up
private void addDispatcherContext(ServletContext container) {
  // Create the dispatcher servlet's Spring application context
  AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();
  dispatcherContext.register(SpringDispatcherConfig.class); 
	 
  // Declare  <servlet> and <servlet-mapping> for the DispatcherServlet
  ServletRegistration.Dynamic dispatcher = container.addServlet("ch07-servlet", 
  		new DispatcherServlet(dispatcherContext));
  dispatcher.addMapping("/");
  dispatcher.setLoadOnStartup(1);
  
 
     
}
 
Example 27
@Test
public void withFlashAttributes() throws Exception {
	UrlFilenameViewController ctrl = new UrlFilenameViewController();
	MockHttpServletRequest request = new MockHttpServletRequest("GET", "/index");
	request.setAttribute(DispatcherServlet.INPUT_FLASH_MAP_ATTRIBUTE, new ModelMap("name", "value"));
	MockHttpServletResponse response = new MockHttpServletResponse();
	ModelAndView mv = ctrl.handleRequest(request, response);
	assertEquals("index", mv.getViewName());
	assertEquals(1, mv.getModel().size());
	assertEquals("value", mv.getModel().get("name"));
}
 
Example 28
Source Project: sinavi-jfw   Source File: JseValidationsTagTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws Exception {

    MockServletContext sc = new MockServletContext();
    request = new MockHttpServletRequest(sc);
    response = new MockHttpServletResponse();
    page = new MockPageContext(sc, request, response);
    request.setAttribute(DispatcherServlet.OUTPUT_FLASH_MAP_ATTRIBUTE, new FlashMap());
}
 
Example 29
Source Project: springMvc4.x-project   Source File: WebInitializer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void onStartup(ServletContext servletContext)
		throws ServletException {
	AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
	ctx.register(MyMvcConfig.class);
	ctx.setServletContext(servletContext); // ②

	Dynamic servlet = servletContext.addServlet("dispatcher",new DispatcherServlet(ctx)); // 3
	servlet.addMapping("/");
	servlet.setLoadOnStartup(1);
}
 
Example 30
@Test
public void withFlashAttributes() throws Exception {
	UrlFilenameViewController ctrl = new UrlFilenameViewController();
	MockHttpServletRequest request = new MockHttpServletRequest("GET", "/index");
	request.setAttribute(DispatcherServlet.INPUT_FLASH_MAP_ATTRIBUTE, new ModelMap("name", "value"));
	MockHttpServletResponse response = new MockHttpServletResponse();
	ModelAndView mv = ctrl.handleRequest(request, response);
	assertEquals("index", mv.getViewName());
	assertEquals(1, mv.getModel().size());
	assertEquals("value", mv.getModel().get("name"));
}