我已经创建了 web 应用程序,我想知道在 web.xml 中我的监听器放在哪里。
<servlet>
<servlet-name>ProcessReg</servlet-name>
<servlet-class>ProcessReg</servlet-class>
<init-param>
<param-name>pract123</param-name>
<param-value>jdbc:odbc:practODBC</param-value>
</init-param>
<listener>
<listener-class>config</listener-class>
</listener>
</servlet>
我收到的错误信息是:
cvc-complex-type.2.4.a: Invalid content was found starting with element 'listener'. One of '{"http://java.sun.com/xml/ns/javaee":init-param, "http://java.sun.com/xml/ns/javaee":load-on-startup, "http://java.sun.com/xml/ns/javaee":run-as, "http://java.sun.com/xml/ns/javaee":security-role-ref}' is expected. [17]
这是我的配置文件:
public class config implements ServletContextListener {
private static final String ATTRIBUTE_NAME = "config";
private DataSource dataSource;
@Override
public void contextInitialized(ServletContextEvent event) {
ServletContext servletContext = event.getServletContext();
String databaseName = servletContext.getInitParameter("pract123");
try {
dataSource = (DataSource) new InitialContext().lookup("java:/comp /env/jdbc/TestDB");
} catch (NamingException e) {
throw new RuntimeException("Config failed: datasource not found", e);
}}
@Override
public void contextDestroyed(ServletContextEvent event) {
// NOOP.
}
public DataSource getDataSource() {
return dataSource;
}
public static config getInstance(ServletContext servletContext) {
return (config) servletContext.getAttribute(ATTRIBUTE_NAME);
}
}