首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何访问servlet上下文侦听器中的属性?

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

Stack Overflow用户
提问于 2015-04-14 13:03:03
回答 2查看 1.9K关注 0票数 0

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

下面是我的上下文侦听器(导入了必要的类):

代码语言:javascript
运行
复制
 @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:

代码语言:javascript
运行
复制
 <web-app>
    <listener>
<listener-class>
    Listener.MyServletContextListener
</listener-class>
</listener>

这是我的jsp:

代码语言:javascript
运行
复制
    <%
    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属性?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-04-14 15:44:14

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

票数 0
EN

Stack Overflow用户

发布于 2015-04-14 13:10:00

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

代码语言:javascript
运行
复制
catch(ClassNotFoundException ex){
     System.out.println(ex) 
}
catch(SQLException sqle){
 System.out.println(sqle)
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29628086

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档