SSH_框架整合4--添加员工信息
一、
1 index.jsp:添加:<a href="emp-input">添加员工向信息:Add Employees' Information</a>
2 因为在添加员工信息时要选择员工的部门信息,所以要先获取Department信息:
(1)com.atguigu.ssh.dao中:提取EmployeeDao.java中公共部分代码(getSession())作为父类BaseDao
SSH_框架整合4--添加员工信息
新建DepartmentDao类来获取Department集合信息:DepartmentDao.java
package com.atguigu.ssh.dao; import java.util.List; import com.atguigu.ssh.entities.Department; public class DepartmentDao extends BaseDao{ //获取查询到的Department集合
public List<Department> getAll(){
String hql="FROM Department";
return getSession().createQuery(hql).list();
}
}
(2)com.atguigu.ssh.service包中:新建DepartmentService类:DepartmentService.java
package com.atguigu.ssh.service; import java.util.List; import com.atguigu.ssh.dao.DepartmentDao;
import com.atguigu.ssh.entities.Department; public class DepartmentService { private DepartmentDao departmentDao;
public void setDepartmentDao(DepartmentDao departmentDao) {
this.departmentDao = departmentDao;
} public List<Department> getAll(){
return departmentDao.getAll();
}
}
(3) com.atguigu.ssh.actions包下的EmployeeAction.java:填写获取Department集合的方法并且放入request中(jsp页面中就可以通过request直接获取)
//3-1 查询Department
private DepartmentService departmentService;
public void setDepartmentService(DepartmentService departmentService) {
this.departmentService = departmentService;
}
//3-2 实现添加员工信息的方法
public String input(){
request.put("departments", departmentService.getAll());
return INPUT;
}
3 完善applicationContext-beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="employeeDao" class="com.atguigu.ssh.dao.EmployeeDao">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean> <bean id="departmentDao" class="com.atguigu.ssh.dao.DepartmentDao">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean> <bean id="employeeService" class="com.atguigu.ssh.service.EmployeeService">
<property name="employeeDao" ref="employeeDao"></property>
</bean> <bean id="departmentService" class="com.atguigu.ssh.service.DepartmentService">
<property name="departmentDao" ref="departmentDao"></property>
</bean> <bean id="employeeAction" class="com.atguigu.ssh.actions.EmployeeAction"
scope="prototype">
<property name="employeeService" ref="employeeService"></property>
<property name="departmentService" ref="departmentService"></property>
</bean>
</beans>
4 完善struts.xml,添加显示添加页面语句:<result name="input">/WEB-INF/views/emp-input.jsp</result>
5 WebContent-WEB-INF-views下新建emp-input.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h4>Employee Input Page</h4> <s:form action="emp-save" method="post">
<s:textfield name="lastName" label="LastName"></s:textfield>
<s:textfield name="email" label="Email"></s:textfield>
<s:textfield name="birth" label="Birth"></s:textfield> <s:select list="#request.departments"
listKey="id" listValue="departmentName" name="department.id"
label="Department"></s:select>
<s:submit></s:submit>
</s:form> </body>
</html>
二、
1 实现ModelDriven拦截器操作
(1)EmployeeAction实现ModelDriven<Employee>,Preparable接口,添加实现方法:
//****
@Override
public void prepare() throws Exception {
}
//****
private Employee model;
//****
@Override
public Employee getModel() {
return model;
}
//**** 4 使用ModelDriven拦截器方法存储添加的信息
public String save(){
System.out.println(model);
model.setCreateTime(new Date());
employeeService.saveorUpdate(model);
return SUCCESS;
}
//****
public void prepareSave(){
model=new Employee();
} //**** 拦截器的方法
public void prepareInput(){ }
(2)Struts.xml配置下拦截器:
<!-- 定义新的拦截器栈,
配置 prepare 拦截器栈的 alwaysInvokePrepare 参数值为 false -->
<interceptors>
<interceptor-stack name="sshStack">
<interceptor-ref name="paramsPrepareParamsStack">
<param name="prepare.alwaysInvokePrepare">false</param>
</interceptor-ref>
</interceptor-stack>
</interceptors>
<!-- 使用新的拦截器栈 -->
<default-interceptor-ref name="sshStack"></default-interceptor-ref>
2 定制类型转换器:使输入的Birth字符串转化为Date类型
(1)新建包com.atguigu.ssh.converters:新建SSHDateConverter.java类
package com.atguigu.ssh.converters; import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map; import org.apache.struts2.util.StrutsTypeConverter; public class SSHDateConverter extends StrutsTypeConverter { private DateFormat dateFormat; public SSHDateConverter()
{
dateFormat = new SimpleDateFormat("yyyy-MM-dd");
} @Override
public Object convertFromString(Map context, String[] values, Class toClass) {
if(toClass == Date.class){
if(values !=null && values.length>0){
String value=values[0];
try {
return dateFormat.parse(value);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
return values;
} @Override
public String convertToString(Map context, Object o) {
if(o instanceof Date){
Date date=(Date)o;
return dateFormat.format(date);
}
return null;
} }
(2)src-cong下新建xwork-conversion.properties,配置类型转换器:
java.util.Date=com.atguigu.ssh.converters.SSHDateConverter
3 实现存储操作:
(1)EmployeeDao.java中添加save方法:
//3 添加、存储
public void saveOrUpadate(Employee employee){
getSession().saveOrUpdate(employee);
}
(2)EmployeeService.java
//3 添加、存储
public void saveorUpdate(Employee employee){
employeeDao.saveOrUpadate(employee);
}
(3)EmployeeAction.java:
//**** 4 使用ModelDriven拦截器方法存储添加的信息
public String save(){
System.out.println(model);
model.setCreateTime(new Date());
employeeService.saveorUpdate(model);
return SUCCESS;
}
//****
public void prepareSave(){
model=new Employee();
}
4 显示页面:格式化时间操作:
<td>
<s:date name="birth" format="yyyy-MM-dd"/>
</td>
<td>
<s:date name="createTime" format="yyyy-MM-dd hh:mm:ss"/>
</td>
结构图:
文件:
1 EmployeeAction.java
package com.atguigu.ssh.actions; import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Map; import org.apache.struts2.interceptor.RequestAware; import com.atguigu.ssh.entities.Employee;
import com.atguigu.ssh.service.DepartmentService;
import com.atguigu.ssh.service.EmployeeService;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable; public class EmployeeAction extends ActionSupport implements RequestAware,
ModelDriven<Employee>,Preparable{ private static final long serialVersionUID = 1L; private EmployeeService employeeService; public void setEmployeeService(EmployeeService employeeService){
this.employeeService=employeeService;
} //**** 4 使用ModelDriven拦截器方法存储添加的信息
public String save(){
System.out.println(model);
model.setCreateTime(new Date());
employeeService.saveorUpdate(model);
return SUCCESS;
}
//****
public void prepareSave(){
model=new Employee();
} //3-1 查询Department
private DepartmentService departmentService;
public void setDepartmentService(DepartmentService departmentService) {
this.departmentService = departmentService;
}
//3-2 实现添加员工信息的方法
public String input(){
request.put("departments", departmentService.getAll());
return INPUT;
} //**** 拦截器的方法
public void prepareInput(){ } //2 删除
private Integer id;
public void setId(Integer id) {
this.id = id;
}
/*public String delete(){
employeeService.delete(id);
return SUCCESS;
}*/
//2-1 使用Ajax方式删除
private InputStream inputStream; public InputStream getInputStream() {
return inputStream;
} public String delete(){
employeeService.delete(id);
try {
//删除成功
inputStream=new ByteArrayInputStream("1".getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
//删除失败
try {
inputStream=new ByteArrayInputStream("0".getBytes("UTF-8"));
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
e.printStackTrace();
}
return "ajax-delete-success";
}
//1 查询
public String list(){
request.put("employees", employeeService.getAll());
return "list";
} //放到页面里
private Map<String,Object> request; @Override
public void setRequest(Map<String, Object> arg0) {
this.request=arg0;
} //****
@Override
public void prepare() throws Exception {
}
//****
private Employee model;
//****
@Override
public Employee getModel() {
return model;
} }
2 struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd"> <struts> <constant name="struts.enable.DynamicMethodInvocation" value="false" />
<constant name="struts.devMode" value="true" /> <package name="default" namespace="/" extends="struts-default">
<!-- 定义新的拦截器栈,
配置 prepare 拦截器栈的 alwaysInvokePrepare 参数值为 false -->
<interceptors>
<interceptor-stack name="sshStack">
<interceptor-ref name="paramsPrepareParamsStack">
<param name="prepare.alwaysInvokePrepare">false</param>
</interceptor-ref>
</interceptor-stack>
</interceptors>
<!-- 使用新的拦截器栈 -->
<default-interceptor-ref name="sshStack"></default-interceptor-ref> <action name="emp-*" class="employeeAction"
method="{1}">
<result name="list">/WEB-INF/views/emp-list.jsp</result> <result type="stream" name="ajax-delete-success">
<param name="contentType">text/html</param>
<param name="inputName">inputStream</param>
</result>
<result name="input">/WEB-INF/views/emp-input.jsp</result> <result name="success" type="redirect">/emp-list</result>
</action>
</package> </struts>
3 emp-list.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" SRC="scripts/jquery-1.7.2.js"></script>
<script type="text/javascript">
//删除, 使用 ajax 的方式
$(function(){
$(".delete").click(function(){
var lastName=$(this).next(":input").val();
var flag=confirm("是否要删除"+lastName+"的信息吗?");
//确认删除, 使用 ajax 的方式
if(flag){
//获取要删除的行
var $tr=$(this).parent().parent();
var url=this.href;
var args={"time":new Date()};
$.post(url,args,function(data){
//若 data 的返回值为 1, 则提示 删除成功, 且把当前行删除
if(data==1){
alert("删除成功!");
$tr.remove();
}else{
//若 data 的返回值不是 1, 提示删除失败.
alert("删除失败!");
}
});
}
return false;
});
})
</script>
</head>
<body>
<h3>Employee List Page</h3> <s:if test="#request.employees == null ||#request.size()==0">
没有员工信息
</s:if>
<s:else>
<table border="1" cellpadding="10" cellspacing="0">
<tr>
<td>ID</td>
<td>LASTNAME</td>
<td>EMAIL</td>
<td>BIRTH</td>
<td>CREATETIME</td>
<td>DEPT</td>
</tr>
<s:iterator value="#request.employees">
<tr>
<td>${id}</td>
<td>${lastName}</td>
<td>${email }</td>
<%--
<td>${birth}</td>
<td>${createTime}</td>
--%>
<td>
<s:date name="birth" format="yyyy-MM-dd"/>
</td>
<td>
<s:date name="createTime" format="yyyy-MM-dd hh:mm:ss"/>
</td> <td>${department.departmentName}</td>
<td>
<a href="emp-delete?id=${id }" class="delete">Delete</a>
<input type="hidden" value="${lastName}"/>
</td>
</tr>
</s:iterator>
</table>
</s:else>
</body>
</html>
4 emp-input.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h4>Employee Input Page</h4> <s:form action="emp-save" method="post">
<s:textfield name="lastName" label="LastName"></s:textfield>
<s:textfield name="email" label="Email"></s:textfield>
<s:textfield name="birth" label="Birth"></s:textfield> <s:select list="#request.departments"
listKey="id" listValue="departmentName" name="department.id"
label="Department"></s:select>
<s:submit></s:submit>
</s:form> </body>
</html>