package demo;If the
public class FooServlet extends HttpServlet {
@Resource(name="jdbc/mysql-ds")
private DataSource dataSource;
protected void doGet(
HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
Connection con = null;
Connection conn = null;
try {
InitialContext ic = new InitialContext();
DataSource ds =
(DataSource) ic.lookup("java:comp/env/jdbc/mysql-ds");
//the following 2 statements work the same:
conn = dataSource.getConnection();
con = ds.getConnection();
} catch (NamingException ex) {
throw new ServletException(ex);
} catch (SQLException ex) {
throw new ServletException(ex);
} finally {
//close con conn here
}
}
}
name()
field is not specified for @EJB
or @Resource
, the default jndi name is not the variable name; instead, it's in the form of fully-qualified-classname/variable-name. Therefore, using default jndi name, the above example needs to be rewrite as follows:package demo;
public class FooServlet extends HttpServlet {
@Resource
private DataSource dataSource;
protected void doGet(
HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
Connection con = null;
Connection conn = null;
try {
InitialContext ic = new InitialContext();
DataSource ds = (DataSource) ic.lookup(
"java:comp/env/demo.FooServlet/dataSource");
//the following 2 statements work the same:
conn = dataSource.getConnection();
con = ds.getConnection();
} catch (NamingException ex) {
throw new ServletException(ex);
} catch (SQLException ex) {
throw new ServletException(ex);
} finally {
//close con conn here
}
}
}
Tags: