spring 无法解析未找到 WebApplicationContext:未注册 ContextLoaderListener
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23857564/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cannot resolve No WebApplicationContext found: no ContextLoaderListener registered
提问by user3673985
I'm trying to create Spring web application with annotations only(no configuration xml files). I am using tomcat as application server and maven for build the project. Googled a lot, modified a lot but still stuck with this error. Please find below the files. Hope some one can help me. Thanks in advance. :)
我正在尝试创建仅带有注释的 Spring Web 应用程序(没有配置 xml 文件)。我使用 tomcat 作为应用程序服务器和 maven 来构建项目。谷歌搜索了很多,修改了很多,但仍然坚持这个错误。请在下面找到文件。希望可以有人帮帮我。提前致谢。:)
Below is the pom.xml
下面是 pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mycompany.app</groupId>
<artifactId>Angular</artifactId>
<packaging>war</packaging>
<version>0.1</version>
<name>Angular Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>3.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-hibernate3</artifactId>
<version>2.0.8</version>
<exclusions>
<exclusion>
<artifactId>hibernate</artifactId>
<groupId>org.hibernate</groupId>
</exclusion>
<exclusion>
<artifactId>servlet-api</artifactId>
<groupId>javax.servlet</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons-core</artifactId>
<version>1.4.1.RELEASE</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>sqljdbc4</artifactId>
<version>4.0</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>3.6.10.Final</version>
<optional>true</optional>
<exclusions>
<exclusion>
<artifactId>asm</artifactId>
<groupId>asm</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>3.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-dao</artifactId>
<version>2.0.8</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>3.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<finalName>Angular</finalName>
</build>
</project>
the initializer file
初始化文件
package com.sample.main;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import com.sample.configuration.Configurations;
import com.sample.configuration.MvcConfigurations;
public class WebAppInitializer implements WebApplicationInitializer {
public void onStartup(ServletContext servletContext)
throws ServletException {
// TODO Auto-generated method stub
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.register(Configurations.class);
rootContext.refresh();
servletContext.addListener(new ContextLoaderListener(rootContext));
servletContext.setInitParameter("defaultHtmlEscape", "true");
AnnotationConfigWebApplicationContext mvcContext = new AnnotationConfigWebApplicationContext();
mvcContext.register(MvcConfigurations.class);
mvcContext.refresh();
ServletRegistration.Dynamic dispatcher = servletContext.addServlet(
"dispatcher", new DispatcherServlet(mvcContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/test/*");
}
}
The MVC configuration files
MVC 配置文件
package com.sample.configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
@Configuration
@EnableWebMvc
@ComponentScan(basePackages={"com.sample.controller"})
public class MvcConfigurations {
@Bean
public InternalResourceViewResolver viewResolver(){
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/req/");
resolver.setSuffix(".jsp");
return resolver;
}
}
** The root configuration **
** 根配置 **
package com.sample.configuration;
import java.util.Properties;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.hibernate4.HibernateExceptionTranslator;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.orm.jpa.vendor.HibernateJpaDialect;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories("com.sample.repo")
@ComponentScan("com.sample")
public class Configurations {
@Bean
public DataSource dataSource(){
BasicDataSource basicDataSource = new BasicDataSource();
basicDataSource.setUrl("jdbc:sqlserver://127.0.0.1:1433;databaseName=Garuda");
basicDataSource.setUsername("sa");
basicDataSource.setPassword("garuda123");
basicDataSource.setDriverClassName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
basicDataSource.setMaxActive(5);
basicDataSource.setMinIdle(3);
return basicDataSource;
}
/*@Bean
public PersistenceExceptionTranslationPostProcessor persistenceExceptionTranslationPostProcessor(){
PersistenceExceptionTranslationPostProcessor processor = new PersistenceExceptionTranslationPostProcessor();
return processor;
}*/
@Bean
public HibernateExceptionTranslator hibernateExceptionTranslator(){
HibernateExceptionTranslator exceptionTranslator = new HibernateExceptionTranslator();
return exceptionTranslator;
}
@Bean
public EntityManagerFactory entityManagerFactory(){
LocalContainerEntityManagerFactoryBean bean = new LocalContainerEntityManagerFactoryBean();
bean.setDataSource(dataSource());
bean.setPackagesToScan("com.sample.domain");
HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
jpaVendorAdapter.setDatabase(Database.SQL_SERVER);
//jpaVendorAdapter.setGenerateDdl(true);
//jpaVendorAdapter.setShowSql(true);
bean.setJpaDialect(new HibernateJpaDialect());
bean.setJpaProperties(hibernateProperties());
bean.setJpaVendorAdapter(jpaVendorAdapter);
bean.afterPropertiesSet();
return bean.getObject();
}
@Bean
public JpaTransactionManager transactionManager(){
JpaTransactionManager jpaTransactionManager = new JpaTransactionManager();
jpaTransactionManager.setEntityManagerFactory(entityManagerFactory());
return jpaTransactionManager;
}
public Properties hibernateProperties(){
Properties properties = new Properties();
properties.put("hibernate.hbm2ddl.auto", "update");
properties.put("hibernate.show_sql", "true");
properties.put("hibernate.format_sql", "true");`enter code here`
return properties;
}
}
The controller file
控制器文件
package com.sample.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.sample.domain.Aircraft;
import com.sample.repo.AircraftRepo;
import com.sample.repo.MaintenanceCheckRepo;
import com.sample.vo.AircraftVO;
@Controller
public class MvcController {
@Autowired
AircraftRepo aircraftRepo;
@Autowired
MaintenanceCheckRepo maintenanceCheckRepo;
@RequestMapping("/addAircraft")
public ModelAndView addAircraft(@ModelAttribute AircraftVO aircraftVO) {
ModelAndView view = new ModelAndView();
Aircraft aircraft = aircraftRepo.saveAndFlush(convertVOToEntity(aircraftVO));
view.getModelMap().addAttribute("aircraftVO", convertEntityToVO(aircraft));
view.setViewName("index");
return view;
}
public Aircraft convertVOToEntity(AircraftVO aircraftVO){
Aircraft aircraft = new Aircraft();
aircraft.setAircraftRegistration(aircraftVO.getAircraftRegistration());
aircraft.setAircraftSubType(null);
return aircraft;
}
public AircraftVO convertEntityToVO(Aircraft aircraft){
AircraftVO aircraftVO = new AircraftVO();
aircraftVO.setAircraftRegistration(aircraft.getAircraftRegistration());
aircraftVO.setAircraftSubtypeVO(null);
aircraftVO.setId(aircraft.getId());
return aircraftVO;
}
}
The repository
存储库
package com.sample.repo;
import org.springframework.data.jpa.repository.JpaRepository;
import com.sample.domain.Aircraft;
public interface AircraftRepo extends JpaRepository<Aircraft,Long>{
}
index.jsp
索引.jsp
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<body>
<h2>Hello World!</h2>
<form:form method="post" action="test/addAircraft"
commandName="aircraftVO">
<table>
<tr>
<td>Aircraft Reg No:</td>
<td><form:input path="aircraftRegistration" /></td>
</tr>
<tr>
<input type="submit" value="Add Aircraft" />
</tr>
</table>
</form:form>
</body>
</html>
Web.xml
网页.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
Adding stackTrace:
添加堆栈跟踪:
SEVERE: Servlet.service() for servlet [jsp] in context with path [/Angular] threw exception [An exception occurred processing JSP page /index.jsp at line 5
2: <html>
3: <body>
4: <h2>Hello World!</h2>
5: <form:form method="post" action="test/addAircraft"
6: commandName="aircraftVO">
7: <table>
8: <tr>
Stacktrace:] with root cause
java.lang.IllegalStateException: No WebApplicationContext found: no ContextLoaderListener registered?
at org.springframework.web.context.support.WebApplicationContextUtils.getRequiredWebApplicationContext(WebApplicationContextUtils.java:90)
at org.springframework.web.servlet.support.RequestContextUtils.getWebApplicationContext(RequestContextUtils.java:85)
at org.springframework.web.servlet.support.RequestContext.initContext(RequestContext.java:209)
at org.springframework.web.servlet.support.JspAwareRequestContext.initContext(JspAwareRequestContext.java:74)
at org.springframework.web.servlet.support.JspAwareRequestContext.<init>(JspAwareRequestContext.java:48)
at org.springframework.web.servlet.tags.RequestContextAwareTag.doStartTag(RequestContextAwareTag.java:77)
at org.apache.jsp.index_jsp._jspx_meth_form_005fform_005f0(index_jsp.java:98)
at org.apache.jsp.index_jsp._jspService(index_jsp.java:65)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:68)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:387)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:363)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:306)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:203)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:108)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:558)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:379)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:242)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:259)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:237)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:281)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
at java.lang.Thread.run(Thread.java:662)
回答by M. Deinum
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
Your web.xml
is wrong. You want to use a ServletContainerInitializer
(the one provided by Spring) which is part of the servlet spec 3.0. However your web.xml makes the container operate in a 2.3 mode. Fix your web.xml.
你web.xml
错了。您想使用一个ServletContainerInitializer
(由 Spring 提供的),它是 servlet 规范 3.0 的一部分。但是,您的 web.xml 使容器以 2.3 模式运行。修复您的 web.xml。
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name>Archetype Created Web Application</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
Next, although not directly related but you will run into problems soon enough, you are mixing different versions of the Spring Framework. Never mix jars from different versions of a framework (not only spring but all frameworks). Tip use a single property to define the version you want to use.
接下来,虽然没有直接关系但你很快就会遇到问题,你正在混合不同版本的 Spring 框架。永远不要混合来自不同版本框架的 jar(不仅是 spring,而且是所有框架)。提示使用单个属性来定义要使用的版本。
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mycompany.app</groupId>
<artifactId>Angular</artifactId>
<packaging>war</packaging>
<version>0.1</version>
<name>Angular Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<spring.version>3.2.9.RELEASE</spring.version>
<spring.data.jpa.version>1.6.0.RELEASE</spring.data.jpa.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>${spring.data.jpa.version}</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>sqljdbc4</artifactId>
<version>4.0</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>3.6.10.Final</version>
<optional>true</optional>
<exclusions>
<exclusion>
<artifactId>asm</artifactId>
<groupId>asm</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>Angular</finalName>
</build>
</project>
I took the liberty to cleanup the pom and upgrade to the newest 3.2 version of Spring.
我冒昧地清理了 pom 并升级到最新的 Spring 3.2 版本。
回答by fmodos
Add the below tag to your web.xml, include it inside the web-app
tag
将以下标签添加到您的web.xml,将其包含在web-app
标签中
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>