StrutsでDataSourceを利用する方法

1.Actionのexecute
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
// TODO Auto-generated method stub
//ユーザとパスワードを取得
LoginForm loginform = (LoginForm)form;
String username = loginform.getUsername();
String password = loginform.getPassword();
System.out.println(“————–“+username+"————-“);
System.out.println(“————–“+password+"————-“);
DataSource ds = this.getDataSource(request, “dataSource");
boolean result = false;
try {
Connection conn = ds.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(“select * from startnews24_user where username='"+username+"' and password='"+password+"'");
if(rs.next()) {
result = true;
} else {
result = false;
}
rs.close();
stmt.close();
conn.close();
if(result) {
return mapping.findForward(“welcome");
} else {
return mapping.getInputForward();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}

2.struts-config.xml
<data-sources>
<data-source key="dataSource" type="org.apache.commons.dbcp.BasicDataSource">
<set-property property="username" value="startnews24_user" />
<set-property property="password" value="startnews24_pwd" />
<set-property property="driverClassName" value="com.mysql.jdbc.Driver" />
<set-property property="url" value="jdbc:mysql://localhost:3306/startnews24-db" />
</data-source>
</data-sources>

3.jarファイル
commons-dbcp.jar,commons-pool.jar,commons-collections.jar

Java

Posted by arkgame