如何访问 servlet 上下文侦听器中的属性?

How to access attribute inside servlet context listener?

我想从 jsp 文件访问我在上下文侦听器中设置的属性。我已经设置了 servlet 侦听器,然后我将侦听器添加到 web.xml。我的 servlet 侦听器将用于连接到数据库。

这是我的上下文监听器(需要class被导入):

 @WebServlet("/MyServletContextListener")
  public class MyServletContextListener implements ServletContextListener{

    public void contextDestroyed(ServletContextEvent event) {
        System.out.println("ServletContextListener destroyed");
    }

        //Run this before web application is started
    public void contextInitialized(ServletContextEvent event) {
        System.out.println("ServletContextListener started");   
        String DriverName = "com.mysql.jdbc.Driver";
        String conURL = "jdbc:mysql://localhost/";
        ServletContext context = event.getServletContext();
        String dbName = context.getInitParameter("dbName");
        String user = context.getInitParameter("user");
        String pass = context.getInitParameter("pw");
        Connection conn = null;
        try{
            Class.forName(DriverName);
            conn = DriverManager.getConnection(conURL+dbName, user,pass);
        }catch(ClassNotFoundException ex){

        }catch(SQLException sqle){

        }
        context.setAttribute("conn", conn);
    }
}

我想从我的 jsp 文件访问 "conn"。

这是我的 xml:

 <web-app>
    <listener>
<listener-class>
    Listener.MyServletContextListener
</listener-class>
</listener>

这是我的 jsp:

    <%
    ServletContext context = getServletContext();
    context.getAttribute("conn");
    System.out.println(context.getAttribute("conn"));
    boolean loginpass = false;
    String login = request.getParameter("login");
    String pw = request.getParameter("password");
    try {
        loginpass = checklogin(login, pw,
                (java.sql.Connection) context.getAttribute("conn"));
    } catch (java.sql.SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
%>

System.out.println(context.getAttribute("conn"))打印出来:null

我不应该是null,应该是连接到数据库的。数据库密码和用户名正确。数据库密码和用户名在 context-param 下的 web.xml 中。如何从 MyServletContextListener 获取 conn 属性?

您的连接代码可能有连接错误打印堆栈跟踪。这样你就会知道实际的问题。

catch(ClassNotFoundException ex){
     System.out.println(ex) 
}
catch(SQLException sqle){
 System.out.println(sqle)
}

在部署程序集中添加 mysql 连接器。 项目文件 -> 属性 -> 部署程序集 -> 添加