gpt4 book ai didi

java - 如何访问 servlet 上下文监听器内的属性?

转载 作者:行者123 更新时间:2023-12-02 04:46:19 25 4
gpt4 key购买 nike

我想从 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

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

最佳答案

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

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

关于java - 如何访问 servlet 上下文监听器内的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29628086/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com