这里写自定义目录标题
- 一.Struts2 文件库的下载
- 二.写个对数据库进行增删改查的实例
- 1.确定已经安装JDK,Eclipse,Tomcat,接下来就可以在Eclipse中写代码了。
- 2.实例要求
- 3.项目的目录结构
- 4.需要的struts2的jar包
- 5.web.xml配置文件代码,web.xml文件放在WEB-INF目录下
- 6.struts.xml配置文件代码,先在WEB-INF目录下新建一个文件夹classes,然后在classes目录下创建struts.xml文件
- 7.页面index.jsp和error.jsp
- 8.JdbcUtils.java代码
- 9.OperatDataMethod.java代码
- 10.OperatData.java代码
- 11.数据库表结构
- 12.我用的是highgoDB数据库 ,用jdbc.properties的读取文件的方法连接的数据库
- 13. 下面是运行程序需要的所有jar包
- 14.用到的知识有js,css,jquery,struts,数据库
- 三.struts请求的生命周期
- 四.struts配置文件
- 五.学习struts总结
一.Struts2 文件库的下载
1.下载地址
http://struts.apache.org/download.cgi
2.点击进入网站的页面
3.往下滑动滚动条,可以看到2.5和2.3版本
4.我下载的是2.3版本,接下在 就以2.3版本为例,我下载的是struts-2.3.36-all.zip
5.下载完成后文件夹里显示的目录结构为
6.开发用的jar包都在lib目录中
二.写个对数据库进行增删改查的实例
1.确定已经安装JDK,Eclipse,Tomcat,接下来就可以在Eclipse中写代码了。
2.实例要求
3.项目的目录结构
4.需要的struts2的jar包
5.web.xml配置文件代码,web.xml文件放在WEB-INF目录下
<?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"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
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>Struts 2</display-name>
<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>
</web-app>
6.struts.xml配置文件代码,先在WEB-INF目录下新建一个文件夹classes,然后在classes目录下创建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>
<constant name="struts.devMode" value="true" />
<package name="helloworld" extends="struts-default">
<action name="operatData" class="com.highgo.struts2.action.OperatData"
method="execute">
<result name="success">/index.jsp</result>
<result name="error">/error.jsp</result>
</action>
</package>
</struts>
7.页面index.jsp和error.jsp
index.jsp代码
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html>
<html>
<head>
<title>struts2操作数据库</title>
<link type="text/css" rel="stylesheet" href="css/style.css">
<script src="js/jquery-3.3.1.min.js"></script>
<script src="js/script.js"></script>
</head>
<body>
<div class="bodyDiv" align="center">
<form action="operatData" method="get">
<table class="buttonTable">
<tr>
<td><input type="submit" value="查询" onclick="selectFun()"></td>
<td><input type="submit" value="新增" onclick="insertFun()"></td>
<td><input type="submit" value="修改" onclick="updateFun()"></td>
<td><input type="submit" value="删除" onclick="deleteFun()"></td>
<td><input type="submit" value="搜索" onclick="searchFun()"></td>
</tr>
</table>
<table>
<tr height="50">
<td width="50">姓名:</td>
<td width="223"><input type="text" name="name" id="name"></td>
<td width="50">年龄:</td>
<td width="223"><input type="text" name="age" id="age"></td>
<td width="50">部门:</td>
<td width="173">
<input type="text" name="department" id="department">
<input type="hidden" name="callMethod" id="callMethod" value="">
<input type="hidden" name="id" id="number" value="">
<input type="hidden" name="deleteTime" id="deleteTime" value="">
<input type="hidden" name="creationTime" id="creationTime" value="">
</td>
</tr>
</table>
</form>
<hr />
<br />
<table class="showTable">
<tr align="center" height="30">
<td width="47">选择</td>
<td width="50">序号</td>
<td width="50">姓名</td>
<td width="50">年龄</td>
<td width="150">部门</td>
<td width="100">删除标志</td>
<td width="160">删除时间</td>
<td width="160">创建时间</td>
</tr>
<s:iterator value="#request.list">
<tr align="center" height="30">
<td><input name="radio" type="radio" onclick="radioFun()"></td>
<td><s:property value="%{id}" /></td>
<td><s:property value="%{name}" /></td>
<td><s:property value="%{age}" /></td>
<td><s:property value="%{department}" /></td>
<td><s:property value="%{deleteFlag}" /></td>
<td><s:property value="%{deleteTime}" /></td>
<td><s:property value="%{creationTime}" /></td>
</tr>
</s:iterator>
</table>
</div>
</body>
</html>
error.jsp代码
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>错误页面</title>
</head>
<body>发生错误!
</body>
</html>
script.js代码
function selectFun() {
$("#callMethod").val("select");
}
function insertFun() {
$("#callMethod").val("insert");
var dateStr = getDate();
$("#creationTime").val(dateStr);
}
function updateFun() {
$("#callMethod").val("update");
}
function deleteFun() {
$("#callMethod").val("delete");
var dateStr = getDate();
$("#deleteTime").val(dateStr);
}
function searchFun() {
$("#callMethod").val("search");
}
function getDate() {
var date = new Date();
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
if (hours < 10) {
var hours = "0" + hours;
}
if (minutes < 10) {
var minutes = "0" + minutes;
}
if (seconds < 10) {
var seconds = "0" + seconds;
}
var dateStr = year + "/" + month + "/" + day + " " + hours + ":" + minutes
+ ":" + seconds;
return dateStr;
}
function radioFun() {
var number = $("input:checked").parents("tr").find("td").eq(1).text();
$("#number").val(number);
var name = $("input:checked").parents("tr").find("td").eq(2).text();
$("#name").val(name);
var age = $("input:checked").parents("tr").find("td").eq(3).text();
$("#age").val(age);
var department = $("input:checked").parents("tr").find("td").eq(4).text();
$("#department").val(department);
}
style.css代码
@charset “UTF-8”;
.bodyDiv {
width: 780px;
height: auto;
border: solid #BBB 1px;
padding: 20px;
margin: auto;
position: absolute;
left: 0;
right: 0;
}
table {
cellspacing: 0px;
cellpadding: 0px;
border-width: 1px 0px 0px 1px;
border-collapse: collapse;
}
table td {
padding: 0;
border-width: 0px 1px 1px 0px;
}
.buttonTable tr {
height: 50px;
text-align: center;
}
.buttonTable td {
width: 154px;
}
.showTable {
border: solid #BBB 1px;
}
.showTable td {
border: solid #BBB 1px;
}
8.JdbcUtils.java代码
package com.highgo.struts2.util;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
import org.slf4j.*;
public class JdbcUtils {
private static String driver;
private static String url;
private static String username;
private static String password;
static {
try {
// 1.通过当前类获取类加载器
ClassLoader classLoader = JdbcUtils.class.getClassLoader();
// 2.通过类加载器的方法获得一个输入流
InputStream is = classLoader.getResourceAsStream("jdbc.properties");
// 3.创建一个properties对象
Properties props = System.getProperties();
// 4.加载输入流
props.load(is);
// 5.获取相关参数的值
driver = props.getProperty("driver");
url = props.getProperty("url");
username = props.getProperty("username");
password = props.getProperty("password");
System.out.println("driver=" + driver + "\n" + "url=" + url + "\n" + "username=" + username + "\n" + "password=" + password);
System.out.println("Get data successful");
} catch (Exception e) {
e.printStackTrace();
System.out.println("Throw Exception : " + e.getMessage());
System.out.println("Get data failed");
}
}
public static Connection getConnection() {
Logger logger = LoggerFactory.getLogger(JdbcUtils.class);
Connection con = null;
try {
logger.info("driver=" + driver + "," + "url=" + url + "," + "username=" + username + "," + "password=" + password);
Class.forName(driver);
con = DriverManager.getConnection(url, username, password);
logger.info("Database connection was successful");
} catch (Exception e) {
e.printStackTrace();
logger.info("Throw Exception : " + e.getMessage());
logger.info("Database connection failed");
}
return con;
}
// Close the result set object
public static void close(ResultSet rs) {
Logger logger = LoggerFactory.getLogger(JdbcUtils.class);
try {
if (rs != null) {
rs.close();
}
} catch (Exception e) {
e.printStackTrace();
logger.info("Throw Exception : " + e.getMessage());
}
}
// Close the preparedStatement object
public static void close(PreparedStatement pstmt) {
Logger logger = LoggerFactory.getLogger(JdbcUtils.class);
try {
if (pstmt != null) {
pstmt.close();
}
} catch (Exception e) {
e.printStackTrace();
logger.info("Throw Exception : " + e.getMessage());
}
}
// Close the result set object
public static void close(Connection con) {
Logger logger = LoggerFactory.getLogger(JdbcUtils.class);
try {
if (con != null) {
con.close();
}
} catch (Exception e) {
e.printStackTrace();
logger.info("Throw Exception : " + e.getMessage());
}
}
}
9.OperatDataMethod.java代码
package com.highgo.struts2.service;
import java.sql.*;
import java.util.*;
import org.slf4j.*;
import com.highgo.struts2.action.OperatData;
import com.highgo.struts2.util.JdbcUtils;
public class OperatDataMethod {
Logger logger = LoggerFactory.getLogger(getClass());
// select data
public List<OperatData> getDayList() {
logger.info("select****start");
String str = "select * from struts2_employee where deleteFlag = '未删除' order by id";
ResultSet rs = null;
PreparedStatement pstmt = null;
Connection con = null;
List<OperatData> list = new ArrayList<OperatData>();
try {
con = JdbcUtils.getConnection();
pstmt = con.prepareStatement(str);
rs = pstmt.executeQuery();
while (rs.next()) {
OperatData data = new OperatData();
data.setId(rs.getInt("id"));
data.setName(rs.getString("name"));
data.setAge(rs.getInt("age"));
data.setDepartment(rs.getString("department"));
data.setDeleteFlag(rs.getString("deleteFlag"));
data.setDeleteTime(rs.getString("deleteTime"));
data.setCreationTime(rs.getString("creationTime"));
list.add(data);
}
logger.info("select successful");
} catch (Exception e) {
e.printStackTrace();
logger.info("Throw Exception : " + e.getMessage());
logger.info("select failed");
} finally {
JdbcUtils.close(rs);
JdbcUtils.close(pstmt);
JdbcUtils.close(con);
}
logger.info("select end");
return list;
}
// insert data
public void insert(String name, int age, String department, String deleteFlag, String deleteTime, String creationTime) {
logger.info("insert++++start");
String str = "insert into struts2_employee(name,age,department,deleteFlag,deleteTime,creationTime) values(?,?,?,?,?,?)";
PreparedStatement pstmt = null;
Connection con = null;
try {
con = JdbcUtils.getConnection();
pstmt = con.prepareStatement(str);
pstmt.setString(1, name);
pstmt.setInt(2, age);
pstmt.setString(3, department);
pstmt.setString(4, deleteFlag);
pstmt.setString(5, deleteTime);
pstmt.setString(6, creationTime);
pstmt.executeUpdate();
logger.info("insert successful");
} catch (Exception e) {
e.printStackTrace();
logger.info("Throw Exception : " + e.getMessage());
logger.info("insert failed");
} finally {
JdbcUtils.close(pstmt);
JdbcUtils.close(con);
}
logger.info("insert end");
}
// update data
public void update(String name, int age, String department, int id) {
logger.info("update____start");
String str = "update struts2_employee set name=?, age=?, department=? where id = ?";
PreparedStatement pstmt = null;
Connection con = null;
try {
con = JdbcUtils.getConnection();
pstmt = con.prepareStatement(str);
pstmt.setString(1, name);
pstmt.setInt(2, age);
pstmt.setString(3, department);
pstmt.setInt(4, id);
pstmt.executeUpdate();
logger.info("update successful");
} catch (Exception e) {
e.printStackTrace();
logger.info("Throw Exception : " + e.getMessage());
logger.info("update failed");
} finally {
JdbcUtils.close(pstmt);
JdbcUtils.close(con);
}
logger.info("update end");
}
// delete data
public void delete(String deleteFlag, String deleteTime, int id) {
logger.info("delete----start");
String str = "update struts2_employee set deleteFlag=?, deleteTime=? where id = ?";
PreparedStatement pstmt = null;
Connection con = null;
try {
con = JdbcUtils.getConnection();
pstmt = con.prepareStatement(str);
pstmt.setString(1, deleteFlag);
pstmt.setString(2, deleteTime);
pstmt.setInt(3, id);
pstmt.executeUpdate();
logger.info("delete successful");
} catch (Exception e) {
e.printStackTrace();
logger.info("Throw Exception : " + e.getMessage());
logger.info("delete failed");
} finally {
JdbcUtils.close(pstmt);
JdbcUtils.close(con);
}
logger.info("delete end");
}
// condition query data
public List<OperatData> getList(String name, int age, String department) {
logger.info("condition query====start");
String str = "select * from struts2_employee where name = ? and age = ? and department = ?";
ResultSet rs = null;
PreparedStatement pstmt = null;
Connection con = null;
List<OperatData> list = new ArrayList<OperatData>();
try {
con = JdbcUtils.getConnection();
pstmt = con.prepareStatement(str);
pstmt.setString(1, name);
pstmt.setInt(2, age);
pstmt.setString(3, department);
rs = pstmt.executeQuery();
while (rs.next()) {
OperatData data = new OperatData();
data.setId(rs.getInt("id"));
data.setName(rs.getString("name"));
data.setAge(rs.getInt("age"));
data.setDepartment(rs.getString("department"));
data.setDeleteFlag(rs.getString("deleteFlag"));
data.setDeleteTime(rs.getString("deleteTime"));
data.setCreationTime(rs.getString("creationTime"));
list.add(data);
}
logger.info("condition query successful");
} catch (Exception e) {
e.printStackTrace();
logger.info("Throw Exception : " + e.getMessage());
logger.info("condition query failed");
} finally {
JdbcUtils.close(rs);
JdbcUtils.close(pstmt);
JdbcUtils.close(con);
}
logger.info("condition query end");
return list;
}
}
10.OperatData.java代码
package com.highgo.struts2.action;
import java.util.*;
import com.highgo.struts2.service.OperatDataMethod;
import com.opensymphony.xwork2.ActionSupport;
public class OperatData extends ActionSupport {
private static final long serialVersionUID = 1L;
private String callMethod;
private int id;
private String name;
private int age;
private String department;
private String deleteFlag;
private String deleteTime;
private String creationTime;
List<OperatData> list = new ArrayList<OperatData>();
OperatDataMethod operatDataMethod = new OperatDataMethod();
public String execute() {
String returnVal = ERROR;
if ("select".equals(callMethod)) {
list = operatDataMethod.getDayList();
returnVal = SUCCESS;
} else if ("insert".equals(callMethod)) {
String flag = "未删除";
String time = "";
operatDataMethod.insert(name, age, department, flag, time, creationTime);
list = operatDataMethod.getDayList();
returnVal = SUCCESS;
} else if ("update".equals(callMethod)) {
operatDataMethod.update(name, age, department, id);
list = operatDataMethod.getDayList();
returnVal = SUCCESS;
} else if ("delete".equals(callMethod)) {
String flag = "已删除";
operatDataMethod.delete(flag, deleteTime, id);
list = operatDataMethod.getDayList();
returnVal = SUCCESS;
} else if ("search".equals(callMethod)) {
list = operatDataMethod.getList(name, age, department);
returnVal = SUCCESS;
}
return returnVal;
}
public String getCallMethod() {
return callMethod;
}
public void setCallMethod(String callMethod) {
this.callMethod = callMethod;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public String getDeleteFlag() {
return deleteFlag;
}
public void setDeleteFlag(String deleteFlag) {
this.deleteFlag = deleteFlag;
}
public String getDeleteTime() {
return deleteTime;
}
public void setDeleteTime(String deleteTime) {
this.deleteTime = deleteTime;
}
public String getCreationTime() {
return creationTime;
}
public void setCreationTime(String creationTime) {
this.creationTime = creationTime;
}
public List<OperatData> getList() {
return list;
}
public void setList(List<OperatData> list) {
this.list = list;
}
}
11.数据库表结构
create table struts2_employee
(
id serial,
name varchar,
age integer,
department varchar,
deleteFlag varchar,
deleteTime varchar,
creationTime varchar
)
12.我用的是highgoDB数据库 ,用jdbc.properties的读取文件的方法连接的数据库
13. 下面是运行程序需要的所有jar包
14.用到的知识有js,css,jquery,struts,数据库
三.struts请求的生命周期
- 用户发送一个资源需求的请求到服务器(例如:页面)。
- 核心控制器查看请求后确定适当的动作。
- 使用验证、文件上传等配置拦截器功能。
- 执行选择的动作来完成请求的操作。
- 另外,如果需要的话,配置的拦截器可做任何后期处理。
- 最后,由视图显示结果并返回给用户。
四.struts配置文件
- web.xml
- struts.xml
- struts-config.xml
- struts.properties
实际上,可以继续依赖于使用web.xml和struts.xml配置文件
五.学习struts总结
Struts2 是一种MVC架构,模型,视图,控制器,可以直接用name属性的标准的getter和setter方法获取值。并且在与数据库进行数据交互的时候,不需要转换数据类型。
struts学习教程网址:https://www.w3cschool.cn/struts_2/