下面是动作类执行方法..
我一直在尝试访问listener设置的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");
答案 0 :(得分:1)
从Struts操作中获取ServletContext
的合法方法是使用request
参数。
ServletContext sc = request.getServletContext();
然后您可以使用sc
来获取属性。