【问题标题】:How to access context attribute in action class of Struts 1.x..?如何访问 Struts 1.x.. 的动作类中的上下文属性?
【发布时间】: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 发布它们

标签: servlets struts-1


【解决方案1】:

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

ServletContext sc = request.getServletContext();

那么你可以使用sc来获取属性。

【讨论】:

    猜你喜欢
    • 2013-06-12
    • 2011-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-09
    • 1970-01-01
    • 2015-06-20
    • 1970-01-01
    相关资源
    最近更新 更多