Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/347.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Servlets 如何访问Struts 1.x的action类中的上下文属性。。?_Servlets_Struts 1 - Fatal编程技术网

Servlets 如何访问Struts 1.x的action类中的上下文属性。。?

Servlets 如何访问Struts 1.x的action类中的上下文属性。。?,servlets,struts-1,Servlets,Struts 1,下面是action类的执行方法 我一直在尝试访问侦听器设置的servletcontext属性 public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { EmployeeForm eForm = (EmployeeForm)

下面是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");
}
执行时,在第行显示空指针异常

Connection con = (Connection)getServlet().getServletContext().getAttribute("database");
从Struts操作中获取信息的合法方法是使用
request
参数

ServletContext sc = request.getServletContext();

然后您可以使用
sc
获取属性。

您确定在方法中提供的
数据库的键值是否存在吗?我确实在listener的ContextInitialized方法中使用键值数据库设置了属性。您是如何在项目中指定listener类的?我是说struts-config.xml或web.xml发布它们
ServletContext sc = request.getServletContext();