@Override
protected ActionForward unspecified(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
DataSource dataSource = (DataSource) new InitialContext().lookup("java:jboss/STRUTS-DS");
dataSource.getConnection();
SessionBean sessionBean = new SessionBean();
sessionBean.testConnection();
return mapping.findForward("list");
}
在Action中,与查找一起使用,SessionBean
@Stateless
public class SessionBean {
@PersistenceContext(???)
EntityManager entityManager;
@Resource(???)
DataSource dataSource;
public void testConnection() {
PreparedStatement preparedStatement = null;
Connection connection = null;
try {
connection = dataSource.getConnection();
preparedStatement = connection.prepareStatement("drop table test");
preparedStatement.execute();
preparedStatement = connection.prepareStatement("CREATE TABLE example (id INT,data VARCHAR(100));");
preparedStatement.execute();
System.out.println("Done");
} catch (SQLException sqlE) {
throw new EJBException(sqlE);
} finally {
try {
if (preparedStatement != null) {
preparedStatement.close();
}
} catch (Exception e) {}
try {
if (connection != null) {
connection.close();
}
} catch (Exception e) {}
}
}
}
我正在尝试注入此内容。 在我的数据源中从未注入过,我在Resource中放了什么?
抱歉:Lorem ipsum dolor sit amet,consectetuer adipiscing elit,sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat。
答案 0 :(得分:0)
尝试在无状态bean中注入DataSource
,并使用它的JNDI名称,如
@Resource(lookup = "java:jboss/STRUTS-DS")
private DataSource dataSource;
您还需要使用@EJB
或@Inject
注释或使用JNDI查找将此无状态注入客户端,这些是您如何确保容器正确注入所有依赖项的唯一方法(在您的情况下为DataSource
)到bean中。