嗨,我有下面的 servletcontextlistener 代码。
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpServlet;
public class ContextListener extends HttpServlet implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
ServletContext context=sce.getServletContext();
String dburl=context.getInitParameter("dbUrl");
String dbusername=context.getInitParameter("dbUserName");
String dbpassword=context.getInitParameter("dbPassword");
DBConnector.createConnection(dburl, dbusername, dbpassword);
System.out.println("Connection Establised.........");
}
public void contextDestroyed(ServletContextEvent sce) {
DBConnector.closeConnection();
}
}
和一个 DBConnector 类如下。
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBConnector {
private static Connection con;
public static void createConnection(String dbUrl,String dbusername,String dbPassword){
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection(dbUrl, dbusername, dbPassword);
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static Connection getConnection(){
return con;
}
public static void closeConnection(){
if(con!=null){
try {
con.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
}
在 web.xml 我声明如下
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 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">
<context-param>
<param-name>dbUrl</param-name>
<param-value>jdbc:oracle:thin:@localhost:1521:XE</param-value>
</context-param>
<context-param>
<param-name>dbUserName</param-name>
<param-value>dbUserName</param-value>
</context-param>
<context-param>
<param-name>dbPassword</param-name>
<param-value>dbPassword</param-value>
</context-param>
<listener>
<listener-class>Topical.ContextListener</listener-class>
</listener>
<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>Login</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/Login</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>
在这里,当我尝试运行 ContextListener.java 时,我抛出了一个错误,提示“类'上下文侦听器'既没有主要方法,也没有在 web.xml 中指定 servlet”。
我如何摆脱这个问题。
谢谢