【发布时间】:2014-04-18 08:38:53
【问题描述】:
下面是action类的执行方法..
我一直在尝试访问监听器设置的 servletcontext 属性..
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
EmployeeForm eForm = (EmployeeForm) form;
String colName = eForm.getColumnName();
List<String> aList = new ArrayList<String>();
Connection con =(Connection)getServlet().getServletContext().getAttribute("database");
try {
PreparedStatement ps = con.prepareStatement("select " + colName + " from emp");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
aList.add(rs.getString(1));
}
request.setAttribute("arraylist", aList);
return mapping.findForward(SUCCESS);
} catch (SQLException ex) {
ex.printStackTrace();
}
return mapping.findForward("failure");
}
下面是 ServletContextListener 方法..
public void contextInitialized(ServletContextEvent sce) {
try {
ServletContext sc = sce.getServletContext();
Connection con = null;
String driverName = sc.getInitParameter("driverName");
Class.forName(driverName);
//Loading the driver
String url = "jdbc:postgresql://localhost:5432/Employee";
String username = "postgres";
String password = "postgres";
con = DriverManager.getConnection(url, username, password);
sc.setAttribute("database", con);
} catch (ClassNotFoundException ex) {
} catch (SQLException ex) {
Logger.getLogger(StrutsServletListener.class.getName()).log(Level.SEVERE, null, ex);
}
}
执行时,在该行显示空指针异常
Connection con = (Connection)getServlet().getServletContext().getAttribute("database");
【问题讨论】:
-
你确定方法中提供的
database的键值存在吗? -
我确实在侦听器的上下文初始化方法中使用键值数据库设置了属性..
-
你是如何在你的项目中指定你的监听类的?我的意思是 struts-config.xml 或 web.xml 发布它们