如何在Struts 1.x的动作类中访问上下文属性?

时间:2014-04-18 08:38:54

标签: servlets struts-1

下面是动作类执行方法..

我一直在尝试访问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");

1 个答案:

答案 0 :(得分:1)

从Struts操作中获取ServletContext的合法方法是使用request参数。

ServletContext sc = request.getServletContext();

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