[英]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.