Question

Below is the action class execute method..

I have been trying to access the servletcontext attribute set by listener..

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");
}

Below is the ServletContextListener method..

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);
    }
}

On execution, shows null pointer exception at the line

Connection con = (Connection)getServlet().getServletContext().getAttribute("database");
Was it helpful?

Solution

The legal way to get ServletContext from the Struts action is using a request parameter.

ServletContext sc = request.getServletContext();

then you can use sc to get attributes.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top