[英]What's the intended use of `servlet-context.xml`, `root-context.xml` and `web.xml`?
我是Java Spring MVC Web開發的新手。 我對下面的3個配置文件感到困惑。 它們由STS webmvc項目模板自動創建。
root-context.xml
是Spring Root Application Context Configuration。 這是可選的。 它用於配置非Web bean。 但是你需要它用於Spring Security或OpenEntityManagerInView Filter。 將它放在meta-inf/spring
會更好。
servlet-context.xml
是Spring Web應用程序上下文配置。 它用於在Web應用程序中配置Spring bean。 如果使用root-context.xml
,則應將非Web bean放在root-context.xml
,將web bean放在servlet-context.xml
。
web.xml
用於配置servlet容器 ,例如Tomcat。 你也需要這個。 它用於配置servlet過濾器和servlet。 首先加載web.xml
,然后可選地加載根上下文,然后加載Web上下文。
您可以通過使用JavaConfig避免使用xml。
創建文件名“javax.servlet.ServletContainerInitializer”(不帶引號)文件內容將是實現此接口的類的完全限定名稱,將文件放在/ META-INF / services
您可以實現ServletContainerInitializer並覆蓋此方法
public class CourtServletContainerInitializer implements ServletContainerInitializer {
@Override
public void onStartup(Set<Class<?>> c, ServletContext ctx) throws ServletException {
AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
applicationContext.register(CourtConfiguration.class);
DispatcherServlet dispatcherServlet = new DispatcherServlet(applicationContext);
ServletRegistration.Dynamic registration = ctx.addServlet("court", dispatcherServlet);
registration.setLoadOnStartup(1);
registration.addMapping("/");
}
}
在此之后,您不需要web.xml
請記住,如果您使用maven構建應用程序,請在pom.xml中提及此內容
<properties>
<failOnMissingWebXml>false</failOnMissingWebXml>
</properties>
在此之前,您必須使用@Configuration和@Bean注釋編寫配置類
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
@Configuration
@ComponentScan(basePackages = "com.practice.learnspringmvc.*")
public class CourtConfiguration {
@Bean
public InternalResourceViewResolver internalResourceViewResolver() {
InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver();
internalResourceViewResolver.setPrefix("/WEB-INF/views/");
internalResourceViewResolver.setSuffix(".jsp");
return internalResourceViewResolver;
}
}
此配置類從servlet-context.xml替換<bean></bean>
初始值設定項
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.