在我的春天應用程序,我有春天環境中的以下配置類:在Spring應用程序使用多個調度servlet的工作
WebAppInitializer.java
@Order(value=1)
public class WebAppInitializer implements WebApplicationInitializer {
@SuppressWarnings("resource")
@Override
public void onStartup(ServletContext container) {
// Create the 'root' Spring application context
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.register(WebAppConfig.class);
// Manage the lifecycle of the root application context
//container.addListener(new ContextLoaderListener(rootContext));
// Create the dispatcher servlet's Spring application context
AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();
dispatcherContext.register(DispatcherConfig.class);
// Register and map the dispatcher servlet
ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(dispatcherContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}
}
WebAppConfig.java
@EnableWebMvc
@EnableTransactionManagement(mode=AdviceMode.PROXY, proxyTargetClass=true)
@ComponentScan(value="spring.webapp.lojavirtual")
@Configuration
public class WebAppConfig extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/bootstrap/**").addResourceLocations("/bootstrap/").setCachePeriod(31556926);
registry.addResourceHandler("/extras/**").addResourceLocations("/extras/").setCachePeriod(31556926);
registry.addResourceHandler("/jquery/**").addResourceLocations("/jquery/").setCachePeriod(31556926);
}
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
DispatcherConfig.java
@Controller
@Import(WebAppConfig.class)
public class DispatcherConfig {
@Bean
public ViewResolver jspResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/jsp/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
我想添加其他調度的servlet我的應用程序。我的第一個想法是屁股下面的代碼上面的類:
在WebAppInitializer.java
一個新的塊這樣的,更改其名稱,在適當的地方:
// Create the dispatcher servlet's Spring application context
AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();
dispatcherContext.register(DispatcherConfig.class);
// Register and map the dispatcher servlet
ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(dispatcherContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
並添加一個新的類如DispatcherConfig.java,在上面的代碼中選擇了該名稱。
我的問題是:
1)首先,我的做法是添加一個新的分發程序Servlet的正確方法?
2)其次,如果問題1的答案是「是」,這名字,我應該在WebAppInitializer改變?
3)在我的控制器(S),我該怎麼sinalize爲其調度的servlet我徵用應該去?我的控制器使用類似下面的呼叫視圖方法:
@RequestMapping(value="view_mapping")
public method() {
ModelAndView mav = new ModelAndView()
mav.setViewName("view_name");
return mav;
}
你幾乎總是不應該有多個servlet,而應該把所有你需要的映射添加到單個servlet中。你爲什麼認爲你需要更多? – chrylis