org.springframework.web.servlet.DispatcherServlet Java Examples
The following examples show how to use
org.springframework.web.servlet.DispatcherServlet.
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: JdkProxyControllerTests.java From java-technology-stack with MIT License | 6 votes |
@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 #2
Source File: ServletAnnotationControllerTests.java From spring4-understanding with Apache License 2.0 | 6 votes |
@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
Source File: ServletAnnotationControllerTests.java From spring4-understanding with Apache License 2.0 | 6 votes |
@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 #4
Source File: RedirectViewTests.java From spring4-understanding with Apache License 2.0 | 6 votes |
@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 #5
Source File: ResponseEntityExceptionHandlerTests.java From java-technology-stack with MIT License | 6 votes |
@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 #6
Source File: AnnotationConfigDispatcherServletInitializerTests.java From spring4-understanding with Apache License 2.0 | 6 votes |
@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 #7
Source File: UriTemplateServletAnnotationControllerTests.java From spring4-understanding with Apache License 2.0 | 6 votes |
@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 #8
Source File: LayuiAdminStartUp.java From layui-admin with MIT License | 6 votes |
@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 #9
Source File: WebConfigurer.java From flowable-engine with Apache License 2.0 | 6 votes |
/** * 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 #10
Source File: ServletAnnotationControllerTests.java From spring4-understanding with Apache License 2.0 | 6 votes |
@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 #11
Source File: SpringWebInitializer.java From Spring-5.0-Cookbook with MIT License | 6 votes |
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 #12
Source File: TraceeInterceptorSpringApplicationInitializer.java From tracee with BSD 3-Clause "New" or "Revised" License | 6 votes |
@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 #13
Source File: MainWebAppInitializer.java From tutorials with MIT License | 6 votes |
@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 #14
Source File: WebAppConfiguration.java From sakai with Educational Community License v2.0 | 6 votes |
@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 #15
Source File: UriTemplateServletAnnotationControllerTests.java From spring4-understanding with Apache License 2.0 | 6 votes |
@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 #16
Source File: AbstractTagTests.java From java-technology-stack with MIT License | 6 votes |
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 #17
Source File: WebAppConfiguration.java From sakai with Educational Community License v2.0 | 6 votes |
@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 #18
Source File: ViewResolverTests.java From java-technology-stack with MIT License | 5 votes |
@Test public void testInternalResourceViewResolverWithJstl() throws Exception { Locale locale = !Locale.GERMAN.equals(Locale.getDefault()) ? Locale.GERMAN : Locale.FRENCH; MockServletContext sc = new MockServletContext(); StaticWebApplicationContext wac = new StaticWebApplicationContext(); wac.setServletContext(sc); wac.addMessage("code1", locale, "messageX"); wac.refresh(); InternalResourceViewResolver vr = new InternalResourceViewResolver(); vr.setViewClass(JstlView.class); vr.setApplicationContext(wac); View view = vr.resolveViewName("example1", Locale.getDefault()); assertEquals("Correct view class", JstlView.class, view.getClass()); assertEquals("Correct URL", "example1", ((JstlView) view).getUrl()); view = vr.resolveViewName("example2", Locale.getDefault()); assertEquals("Correct view class", JstlView.class, view.getClass()); assertEquals("Correct URL", "example2", ((JstlView) view).getUrl()); MockHttpServletRequest request = new MockHttpServletRequest(sc); HttpServletResponse response = new MockHttpServletResponse(); request.setAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac); request.setAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE, new FixedLocaleResolver(locale)); Map<String, Object> model = new HashMap<>(); TestBean tb = new TestBean(); model.put("tb", tb); view.render(model, request, response); assertTrue("Correct tb attribute", tb.equals(request.getAttribute("tb"))); assertTrue("Correct rc attribute", request.getAttribute("rc") == null); assertEquals(locale, Config.get(request, Config.FMT_LOCALE)); LocalizationContext lc = (LocalizationContext) Config.get(request, Config.FMT_LOCALIZATION_CONTEXT); assertEquals("messageX", lc.getResourceBundle().getString("code1")); }
Example #19
Source File: StandaloneMockMvcBuilder.java From spring4-understanding with Apache License 2.0 | 5 votes |
private void registerMvcSingletons(StubWebApplicationContext wac) { StandaloneConfiguration config = new StandaloneConfiguration(); config.setApplicationContext(wac); wac.addBeans(this.controllerAdvice); StaticRequestMappingHandlerMapping hm = config.getHandlerMapping(); hm.setServletContext(wac.getServletContext()); hm.setApplicationContext(wac); hm.afterPropertiesSet(); hm.registerHandlers(this.controllers); wac.addBean("requestMappingHandlerMapping", hm); RequestMappingHandlerAdapter handlerAdapter = config.requestMappingHandlerAdapter(); handlerAdapter.setServletContext(wac.getServletContext()); handlerAdapter.setApplicationContext(wac); handlerAdapter.afterPropertiesSet(); wac.addBean("requestMappingHandlerAdapter", handlerAdapter); wac.addBean("handlerExceptionResolver", config.handlerExceptionResolver()); wac.addBeans(initViewResolvers(wac)); wac.addBean(DispatcherServlet.LOCALE_RESOLVER_BEAN_NAME, this.localeResolver); wac.addBean(DispatcherServlet.THEME_RESOLVER_BEAN_NAME, new FixedThemeResolver()); wac.addBean(DispatcherServlet.REQUEST_TO_VIEW_NAME_TRANSLATOR_BEAN_NAME, new DefaultRequestToViewNameTranslator()); this.flashMapManager = new SessionFlashMapManager(); wac.addBean(DispatcherServlet.FLASH_MAP_MANAGER_BEAN_NAME, this.flashMapManager); }
Example #20
Source File: RedirectViewTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Test public void http11() throws Exception { RedirectView rv = new RedirectView(); rv.setUrl("http://url.somewhere.com"); rv.setHttp10Compatible(false); MockHttpServletRequest request = createRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); request.setAttribute(DispatcherServlet.OUTPUT_FLASH_MAP_ATTRIBUTE, new FlashMap()); request.setAttribute(DispatcherServlet.FLASH_MAP_MANAGER_ATTRIBUTE, new SessionFlashMapManager()); rv.render(new HashMap<String, Object>(), request, response); assertEquals(303, response.getStatus()); assertEquals("http://url.somewhere.com", response.getHeader("Location")); }
Example #21
Source File: ExceptionHandlerExceptionResolverTests.java From java-technology-stack with MIT License | 5 votes |
@Before public void setup() throws Exception { this.resolver = new ExceptionHandlerExceptionResolver(); this.resolver.setWarnLogCategory(this.resolver.getClass().getName()); this.request = new MockHttpServletRequest("GET", "/"); this.request.setAttribute(DispatcherServlet.OUTPUT_FLASH_MAP_ATTRIBUTE, new FlashMap()); this.response = new MockHttpServletResponse(); }
Example #22
Source File: WebGuestComponentScanRegistrar.java From wallride with Apache License 2.0 | 5 votes |
@Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (DispatcherServletAutoConfiguration.DEFAULT_DISPATCHER_SERVLET_BEAN_NAME.equals(beanName)) { DispatcherServlet dispatcherServlet = (DispatcherServlet) bean; AnnotationConfigServletWebServerApplicationContext context = (AnnotationConfigServletWebServerApplicationContext) dispatcherServlet.getWebApplicationContext(); context.scan(packagesToScan); this.processed = true; } return bean; }
Example #23
Source File: WebInitializer.java From springMvc4.x-project with Apache License 2.0 | 5 votes |
@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); servlet.setAsyncSupported(true);//① }
Example #24
Source File: RequestUtlPatternMapperTest.java From spring-boot-starter-netty with GNU General Public License v3.0 | 5 votes |
private void addPattern() throws ServletException { Servlet obj = new DispatcherServlet(); mapper.addServlet("/json/a/*", obj, "a"); mapper.addServlet("/json/a/b/*", obj, "ab"); mapper.addServlet("/json/b/*", obj, "b"); mapper.addServlet("/json/*", obj, "jsonsall"); mapper.addServlet("/json/", obj, "jsonroot"); mapper.addServlet("/", obj, "root"); }
Example #25
Source File: WebInitializer.java From springMvc4.x-project with Apache License 2.0 | 5 votes |
@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 #26
Source File: SpringWebInitializer.java From Spring-5.0-Cookbook with MIT License | 5 votes |
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("ch02-servlet", new DispatcherServlet(dispatcherContext)); dispatcher.addMapping("*.html"); dispatcher.setLoadOnStartup(1); }
Example #27
Source File: Main.java From backstopper with Apache License 2.0 | 5 votes |
private static DispatcherServlet generateDispatcherServlet(WebApplicationContext context) { DispatcherServlet dispatcherServlet = new DispatcherServlet(context); // By setting dispatcherServlet.setThrowExceptionIfNoHandlerFound() to true we get a NoHandlerFoundException thrown // for a 404 instead of being forced to use error pages. The exception can be directly handled by Backstopper // which is much preferred - you don't lose any context that way. dispatcherServlet.setThrowExceptionIfNoHandlerFound(true); return dispatcherServlet; }
Example #28
Source File: ServletAnnotationControllerTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
@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 #29
Source File: AppInitializer.java From FRC-2018-Public with MIT License | 5 votes |
public void onStartup(ServletContext container) throws ServletException { AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext(); ctx.register(AppConfig.class); ctx.setServletContext(container); ServletRegistration.Dynamic servlet = container.addServlet("dispatcher", new DispatcherServlet(ctx)); servlet.setLoadOnStartup(1); servlet.addMapping("/"); }
Example #30
Source File: FreeMarkerViewTests.java From java-technology-stack with MIT License | 5 votes |
@Test public void validTemplateName() throws Exception { FreeMarkerView fv = new FreeMarkerView(); WebApplicationContext wac = mock(WebApplicationContext.class); MockServletContext sc = new MockServletContext(); Map<String, FreeMarkerConfig> configs = new HashMap<>(); FreeMarkerConfigurer configurer = new FreeMarkerConfigurer(); configurer.setConfiguration(new TestConfiguration()); configurer.setServletContext(sc); configs.put("configurer", configurer); given(wac.getBeansOfType(FreeMarkerConfig.class, true, false)).willReturn(configs); given(wac.getServletContext()).willReturn(sc); fv.setUrl("templateName"); fv.setApplicationContext(wac); MockHttpServletRequest request = new MockHttpServletRequest(); request.addPreferredLocale(Locale.US); request.setAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac); request.setAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE, new AcceptHeaderLocaleResolver()); HttpServletResponse response = new MockHttpServletResponse(); Map<String, Object> model = new HashMap<>(); model.put("myattr", "myvalue"); fv.render(model, request, response); assertEquals(AbstractView.DEFAULT_CONTENT_TYPE, response.getContentType()); }