如何使用Struts 2在Apache Tomcat的web.xml中创建MySQL数据库连接
我想在应用程序级别建立数据库连接,所以我想在Apache tomcat服务器的web.xml
文件中创建连接。 我正在使用Struts2 MVC框架开发我们的应用程序。 实际上我不想在每个Java文件上创建数据库连接。 那么,请给我一个如何在应用程序中建立数据库连接的建议。
我正在尝试在web.xml
创建一个连接,但是在Connection conn = ds.getConnection();
行中显示了像java.lang.NullPointerException
这样的错误Connection conn = ds.getConnection();
。 所有代码都显示在下面
META-INFO/context.xml
:
lib/web.xml
:
MY index.jsp struts2 org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter struts2 /* MySQL Datasource jdbc/dbmy javax.sql.DataSource Container
而我的Action类就像:
import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import javax.annotation.Resource; import javax.servlet.ServletContext; import javax.sql.DataSource; import com.opensymphony.xwork2.*; public class GEtResponseObject extends ActionSupport { /** * */ private static final long serialVersionUID = 1L; ServletContext context =null; PreparedStatement ps =null; ResultSet rs =null; @Resource(name="jdbc/dbmy") private DataSource ds; public String execute() { try{ Connection conn = ds.getConnection(); //At this line, A java.lang.NullPointerException error is being occured. ps = conn.prepareStatement("select * from dbmy.mytable "); rs = ps.executeQuery(); if (rs.next()) { System.out.println(rs.getString("mycolom")); } } catch(SQLException e) { e.printStackTrace(); } return Action.SUCCESS; } }
将@Resource
放在action bean属性上是没有意义的。 如果您需要有关注入资源的更多信息,请阅读教程 。 而是创建一个ServletContextListener
并在那里放置注释。 在上下文初始化事件集上下文属性
public class MyServletContextListener implements ServletContextListener { @Resource(name="jdbc/dbmy") private DataSource ds; @Override public void contextInitialized(ServletContextEvent servletContextEvent) { System.out.println("contextInitialized"); ServletContext context = servletContextEvent.getServletContext(); context.setAttribute("ds",ds); } @Override public void contextDestroyed(ServletContextEvent servletContextEvent) { System.out.println("contextDestroyed"); } }
web.xml
(应该在WEB-INF中):
com.servlet.MyServletContextListener
现在您可以在execute方法中获取数据源
ds = (DataSource)ServletActionContext.getServletContext().getAttribute("ds");