Java Mailing List Archive

http://www.junlu.com/

Home » Home (12/2007) » Struts 2 »

[s2] accessing servlet context from an action

Chris Cheshire

2007-03-23

Replies:

Hi,

I'm familiar with Struts 1, looking at Struts 2. The web app I am
working on needs to use data sources that are controlled by tomcat
connection pooling and accessed through JNDI. For this I need access
to the servlet context that the action is running under.

Previously I had a base action class that all actions extended and
provided a method :

  protected Connection getConnection() {
    Connection conn = null;
    try {
       String datasourceName = "jdbc/" +
getServlet().getServletContext().getInitParameter("database");
       Context initCtx = new InitialContext();
       Context envCtx = (Context)initCtx.lookup("java:comp/env");
       DataSource ds = (DataSource)envCtx.lookup(datasourceName);
       log.debug("retrieving database connection for " + datasourceName);
       conn = ds.getConnection();
       log.debug("done");
       conn.setAutoCommit(false);
       return conn;
    }
    catch (SQLException ex) {
       log.error("error getting a connection", ex);
       return null;
    }
    catch (NamingException ex) {
       log.error("error finding the datasource", ex);
       return null;
    }
  }


However, I am completely lost with Struts 2. Everything servlet
dependent is abstracted away "somewhere". I've been looking at the
tutorials and they don't cover this kind of thing at all.

How do I go about putting the equivalent in an action with Struts 2?

Thanks

Chris

---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscribe@(protected)
For additional commands, e-mail: user-help@(protected)

©2008 junlu.com - Jax Systems, LLC, U.S.A.