10.Struts2连接数据库
链接数据库的两种方式:
1.在Action中连接数据库
2.使用工具类连接数据库
1.在Action中连接数据库
源码文档目录如图所示:
1.建立数据库
数据库建立语句:
create database aynu; use aynu; SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for `person` -- ---------------------------- DROP TABLE IF EXISTS `person`; CREATE TABLE `person` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) DEFAULT NULL, `gender` varchar(255) DEFAULT NULL, `age` int(11) DEFAULT NULL, `city` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of person -- ----------------------------
2.加载struts2核心jar包和数据库驱动包
struts2核心jar包,加载方法略。
xwork-core-2.1.6.jar: Structs2框架的核心类库
struts2-core-2.1.8.1.jar: XWork类库,Structs2在其上构建
ognl-2.7.3.jar:对象图导航语言(Object Graph Navigation Language),Structs2框架通过其读写对象属性。
freemarker-2.3.15.jar: Structs2的UI标签的模板使用FreeMarker编写
commons-logging-1.0.4.jar: ASF出品的日志包,Structs2框架使用这个日志包来支持Log4J和JDK1.4+的日志记录。
commons-fileupload-1.2.1.jar: 文件上传组件,2.1.6版本后必须加入此文件。
数据库驱动包:
mysql-connector-java-3.1.12-bin.jar
3.index.jsp源码如下:
<%@ page pageEncoding="utf-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>register page</title> </head>
<body> <form action="register.action" method="post"> 姓名:<input type="text" name="name"/><br/> 性别:<input type="radio" name="gender" value="male" checked="checked"/>男 <input type="radio" name="gender" value="female"/>女<br/> 年龄:<input type="text" name="age"/><br/> 城市:<input type="text" name="city"/><br/> <input type="submit" value="注册"/> </form> </body> </html>
4.show.jsp源码如下:
<%@ page pageEncoding="utf-8"%> <html> <head> <title>show page</title> </head> <body> 插入完成! </body> </html>
5.RegisterAction.java源码如下:
package cn.edu.aynu.Stu_con_DataSql.actions; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; public class RegisterAction { private String name; private String gender; private int age; private String city; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String execute(){ //将数据插入到数据库 //1.加载数据库驱动 try { String driverName="com.mysql.jdbc.Driver"; Class.forName(driverName); } catch (ClassNotFoundException e) { e.printStackTrace(); } Connection con=null; PreparedStatement ps=null; try { //2.数据库链接 String url="jdbc:mysql://127.0.0.1:3306/aynu"; String user="root"; String password="toor"; con=DriverManager.getConnection(url,user,password);//这里选择import java.sql.Connection; //插入SQL语句 String sql="insert into person(name,gender,age,city)values(?,?,?,?)"; ps=con.prepareStatement(sql); //插入数据 ps.setString(1, name); ps.setString(2, gender); ps.setInt(3, age); ps.setString(4,city); //执行SQL语句插入命令 ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); }finally{ try { ps.close(); con.close(); } catch (SQLException e) { e.printStackTrace(); } } return "success"; } }
6.web.xml配置如下:
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <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> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
7.struts.xml配置如下:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <package name="one" extends="struts-default"> <action name="register" class="cn.edu.aynu.Stu_con_DataSql.actions.RegisterAction"> <result>/show.jsp</result> </action> </package> </struts>
8.部署发布,启动tomcat,地址输入:
http://127.0.0.1:8080/Stu_con_DataSql/
程序截图如下:
数据插入数据库成功!
2.使用工具类连接数据库
只需要修改上面的RegisterAction.java和新增加一个工具类JdbcUtil.java即可。
RegisterAction.java源码如下:
package cn.edu.aynu.Stu_con_DataSql.actions; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import cn.edu.aynu.Stu_con_DataSql.utils.JdbcUtil; public class RegisterAction { private String name; private String gender; private int age; private String city; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String execute(){ //将数据插入到数据库 //1.加载数据库驱动 Connection con=JdbcUtil.getConnection(); PreparedStatement ps=null; try { //插入SQL语句 String sql="insert into person(name,gender,age,city)values(?,?,?,?)"; ps=con.prepareStatement(sql); //插入数据 ps.setString(1, name); ps.setString(2, gender); ps.setInt(3, age); ps.setString(4,city); //执行SQL语句插入命令 ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); }finally{ try { ps.close(); con.close(); } catch (SQLException e) { e.printStackTrace(); } } return "success"; } }
JdbcUtil.java源码如下:
package cn.edu.aynu.Stu_con_DataSql.utils; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; //数据库工具类 public class JdbcUtil { //这里引用import java.sql.Connection; private static Connection con; //1.加载数据库驱动 static{ try { String driverName="com.mysql.jdbc.Driver"; Class.forName(driverName); } catch (ClassNotFoundException e) { e.printStackTrace(); } } //2.数据库链接 public static Connection getConnection(){ String url="jdbc:mysql://127.0.0.1:3306/aynu"; String user="root"; String password="toor"; try { con=DriverManager.getConnection(url,user,password); } catch (SQLException e) { e.printStackTrace(); } return con; } //3.数据库全部关闭 public static void close(Connection con,Statement stmt,ResultSet rs){ //引入java.sql.Satement包,import java.sql.ResultSet,import java.sql.Connection; try { if(con!=null)con.close(); if(stmt!=null)stmt.close(); if(rs!=null)rs.close(); } catch (SQLException e) { e.printStackTrace(); } } //4.数据库选择关闭 public static void close(Object obj){ try { if(obj instanceof Connection &&obj!=null)((Connection)obj).close(); if(obj instanceof Statement &&obj!=null)((Statement)obj).close(); if(obj instanceof ResultSet &&obj!=null)((ResultSet)obj).close(); } catch (SQLException e) { e.printStackTrace(); } } }
重新部署发布,启动tomcat,输入地址:
http://127.0.0.1:8080/Stu_con_DataSql/