0
我想在應用程序級進行數據庫連接,所以我想在Apache Tomcat服務器的web.xml
文件中創建連接。我正在使用Struts2 MVC框架開發我們的應用程序。其實我不想在每個Java文件上創建數據庫連接。所以,請給我一個建議,如何在應用程序中建立數據庫連接。如何在Apache Tomcat的web.xml中使用Struts 2創建MySQL數據庫連接
我正在嘗試在web.xml
中創建連接,但是java.lang.NullPointerException
等錯誤正在Connection conn = ds.getConnection();
處顯示。正在顯示的所有代碼在下面
META-INFO/context.xml
:
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<Resource name="jdbc/dbmy" auth="Container" type="javax.sql.DataSource"
maxActive="50" maxIdle="30" maxWait="10000"
username="root" password="mysql"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/dbmy"/>
</Context>
lib/web.xml
:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>MY</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<resource-ref>
<description>MySQL Datasource</description>
<res-ref-name>jdbc/dbmy</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
</web-app>
我的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;
}
}
你應該接受回答有幫助。 – 2017-12-24 23:53:18