struts2 案例
技术点:
模型驱动
防止表单重复提交–拦截器
数据回显
值栈
OGNL表达式
通配符、路径匹配原则、常量
数据处理的集中方式
请求数据自动封装以及类型转换
1、导包
c3p0-0.9.1.2.jar
commons-dbutils-1.6.jar
commons-fileupload-1.2.2.jar
commons-io-2.0.1.jar
commons-lang3-3.1.jar
freemarker-2.3.19.jar
javassist-3.11.0.GA.jar
mysql-connector-java-5.1.12-bin.jar
ognl-3.0.5.jar
struts2-core-2.3.4.1.jar
xwork-core-2.3.4.1.jar
2、配置web.xml 注册struts核心过滤器
<!-- Struts2的功能的初始化是通过过滤器引入 -->
<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>
3、配置struts.xml
<struts>
<!-- 更改主题 -->
<constant name="struts.ui.theme" value="simple"></constant>
<package name="emp" extends="struts-default">
<!-- 全局视图 -->
<global-results>
<result name="error">/error/error.jsp</result>
</global-results>
<action name="emp_*" class="cn.itcast.action.EmployeeAction" method="{1}">
<!-- 防止表单重复提交,第二步: 配置" 防止表单重复提交拦截器" -->
<interceptor-ref name="defaultStack"></interceptor-ref>
<interceptor-ref name="token">
<!-- 指定拦截哪些方法需要防止表单重复提交(save) -->
<param name="includeMethods">save</param>
</interceptor-ref>
<!-- 防止表单重复提交,第三步: 如果用户重复提交了跳转到指定的错误页面 -->
<result name="invalid.token" type="redirectAction">emp_list</result>
<!-- 首页显示 -->
<result name="list">/WEB-INF/list.jsp</result>
<!-- 进入修改页面 -->
<result name="update">/WEB-INF/update.jsp</result>
<!--
<result name="addsuccess" type="redirectAction">emp_list</result>
-->
</action>
</package>
</struts>
4、开发Action
/**
* 员工管理Action
*
*/
public class EmployeeAction extends ActionSupport implements ModelDriven<Employee>{
/****封装数据****/
private Employee employee = new Employee();
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
// 重写模型驱动方法
@Override
public Employee getModel() {
return employee;
}
/****调用的Service****/
private IEmployeeService employeeService = new EmployeeService();
/**
* 1. 添加员工
*/
public String save() {
try {
// 调用service保存
employeeService.save(employee);
// 添加成功,去到列表页面
return list();
//return "addsuccess";
} catch (Exception e) {
e.printStackTrace();
return ERROR;
}
}
/**
* 2. 列表显示
*/
public String list() {
try {
// 查询全部
List<Employee> listEmp = employeeService.getAll();
// 保存到request域
ActionContext.getContext().getContextMap().put("listEmp", listEmp);
return "list";
} catch (Exception e) {
e.printStackTrace();
return ERROR;
}
}
/**
* 3. 进入修改页面
*/
public String viewUpdate() {
try {
// 3.1 获取当前修改的记录的主键值
int id = employee.getId();
// 3.2 service查询
Employee emp = employeeService.findById(id);
// 3.3 数据回显
// a. 先得到值栈
ValueStack vs = ActionContext.getContext().getValueStack();
vs.pop(); //移除栈顶元素
vs.push(emp); // emp对象放入栈顶
return "update";
} catch (Exception e) {
e.printStackTrace();
return ERROR;
}
}
/**
* 4. 修改员工
*/
public String update() {
try {
// 调用service修改
employeeService.update(employee);
return list();
} catch (Exception e) {
e.printStackTrace();
return ERROR;
}
}
}
5、开发entity
public class Employee {
private int id;// INT PRIMARY KEY AUTO_INCREMENT,
private String empName;// VARCHAR(20),
private Date workDate;// DATE -- 入职时间
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public Date getWorkDate() {
return workDate;
}
public void setWorkDate(Date workDate) {
this.workDate = workDate;
}
}
6、开发dao
创建 – 创建数据库
CREATE DATABASE hib_demo DEFAULT CHARACTER SET utf8;
– 建表
CREATE TABLE employee (
id INT PRIMARY KEY AUTO_INCREMENT,
empName VARCHAR(20),
workDate DATE – 入职时间
)
dao接口
/**
* 数据访问层接口
*
*
*/
public interface IEmployeeDao {
/**
* 查询全部员工
*/
List<Employee> getAll();
/**
* 根据主键查询
*/
Employee findById(int id);
/**
* 添加员工
*/
void save(Employee emp);
/**
* 修改员工
*/
void update(Employee emp);
}
dao方法实现
public class EmployeeDao implements IEmployeeDao{
@Override
public Employee findById(int id) {
String sql = "select * from employee where id=?";
try {
return JdbcUtils.getQuerrRunner().query(sql, new BeanHandler<Employee>(Employee.class),id);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
@Override
public List<Employee> getAll() {
String sql = "select * from employee";
try {
return JdbcUtils.getQuerrRunner().query(sql, new BeanListHandler<Employee>(Employee.class));
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
@Override
public void save(Employee emp) {
String sql = "insert into employee(empName,workDate) values(?,?)";
try {
JdbcUtils.getQuerrRunner().update(sql, emp.getEmpName(),emp.getWorkDate());
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
@Override
public void update(Employee emp) {
String sql = "update employee set empName=?,workDate=? where id=?";
try {
JdbcUtils.getQuerrRunner().update(sql, emp.getEmpName(),emp.getWorkDate(),emp.getId());
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
7、导入 JdbcUtils,以及配置好c3p0
/**
* 封装常用的操作
*
*/
public class JdbcUtils {
// 初始化连接池
private static DataSource dataSource;
static {
dataSource = new ComboPooledDataSource();
}
public static DataSource getDataSource() {
return dataSource;
}
/**
* 创建DbUtils常用工具类对象
*/
public static QueryRunner getQuerrRunner() {
return new QueryRunner(dataSource);
}
}
c3p0配置文件
<c3p0-config>
<default-config>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql:///hib_demo</property>
<property name="user">root</property>
<property name="password">root</property>
<property name="initialPoolSize">5</property>
<property name="maxPoolSize">10</property>
</default-config>
<named-config name="oracleConfig">
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql:///day17</property>
<property name="user">root</property>
<property name="password">root</property>
<property name="initialPoolSize">5</property>
<property name="maxPoolSize">10</property>
</named-config>
</c3p0-config>
8、开发services
/**
* 业务逻辑层接口
*
*
*/
public interface IEmployeeService {
/**
* 查询全部员工
*/
List<Employee> getAll();
/**
* 根据主键查询
*/
Employee findById(int id);
/**
* 添加员工
*/
void save(Employee emp);
/**
* 修改员工
*/
void update(Employee emp);
}
public class EmployeeService implements IEmployeeService{
private IEmployeeDao employeeDao = new EmployeeDao();
@Override
public Employee findById(int id) {
try {
return employeeDao.findById(id);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public List<Employee> getAll() {
try {
return employeeDao.getAll();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public void save(Employee emp) {
try {
employeeDao.save(emp);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public void update(Employee emp) {
try {
employeeDao.update(emp);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
9、相关jsp页面
webroot下 add.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Add</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
</head>
<body>
<s:form action="/emp_save" method="post">
<!-- 防止表单重复提交,第一步:生成id(客户端、服务器) -->
<s:token></s:token>
<table>
<tr>
<td>员工名:</td>
<td><s:textfield name="empName" /></td>
</tr>
<tr>
<td>日期:</td>
<td><s:textfield name="workDate" /></td>
</tr>
<tr>
<td colspan="2">
<s:submit value="保存员工"></s:submit>
</td>
</tr>
</table>
</s:form>
</body>
</html>
WebRoot/WEB-INF 下 list.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>list</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
</head>
<body>
<table border="1" align="center">
<tr>
<th>序号</th>
<th>编号</th>
<th>员工名称</th>
<th>日志日期</th>
<th>操作</th>
</tr>
<!-- 1. 先判断;2. 再迭代 -->
<s:if test="#request.listEmp != null">
<s:iterator var="emp" value="#request.listEmp" status="st">
<tr>
<td><s:property value="#st.count"/></td>
<td><s:property value="#emp.id"/></td>
<td><s:property value="#emp.empName"/></td>
<td><s:property value="#emp.workDate"/></td>
<td>
<s:a href="emp_viewUpdate?id=%{#emp.id}">修改</s:a>
</td>
</tr>
</s:iterator>
</s:if>
<s:else>
<tr>
<td colspan="5">对不起,没有你要显示的数据</td>
</tr>
</s:else>
</table>
</body>
</html>
WebRoot/WEB-INF 下 update.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Add</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
</head>
<body>
<s:form action="/emp_update" method="post">
<!-- 隐藏域,保存主键 -->
<s:hidden name="id"></s:hidden>
<table>
<tr>
<td>员工名:</td>
<td><s:textfield name="empName" /></td>
</tr>
<tr>
<td>日期:</td>
<!--
<td><s:date name="workDate" format="yyyy-MM-dd"/>
<s:hidden name="workDate"></s:hidden>
</td>
-->
<td>
<s:textfield name="workDate" />
</td>
</tr>
<tr>
<td colspan="2">
<s:submit value="修改员工"></s:submit>
</td>
</tr>
</table>
</s:form>
</body>
</html>
时间: 2024-10-04 17:43:22