我想从jsp文件访问我在上下文侦听器中设置的属性。我已经设置了servlet侦听器,然后将侦听器添加到web.xml中。我的servlet监听器将用于连接到数据库。
下面是我的上下文侦听器(导入了必要的类):
 @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,它应该连接到数据库。数据库密码和用户名是正确的。数据库密码和用户名在web.xml中,在context-param下。如何从MyServletContextListener获取conn属性?
发布于 2015-04-14 15:44:14
在部署程序集中添加mysql连接器。项目文件->properites ->部署程序集->添加
发布于 2015-04-14 13:10:00
您的连接代码可能有连接错误,打印堆栈跟踪。这样你就会知道实际的问题了。
catch(ClassNotFoundException ex){
     System.out.println(ex) 
}
catch(SQLException sqle){
 System.out.println(sqle)
}https://stackoverflow.com/questions/29628086
复制相似问题