• SSH_框架整合4--添加员工信息


    SSH_框架整合4--添加员工信息

    一、

    1 index.jsp:添加:<a href="emp-input">添加员工向信息:Add Employees' Information</a>

    2 因为在添加员工信息时要选择员工的部门信息,所以要先获取Department信息:

      (1)com.atguigu.ssh.dao中:提取EmployeeDao.java中公共部分代码(getSession())作为父类BaseDao

      
    1 SSH_框架整合4--添加员工信息
    View Code

        新建DepartmentDao类来获取Department集合信息:DepartmentDao.java

      
     1 package com.atguigu.ssh.dao;
     2 
     3 import java.util.List;
     4 
     5 import com.atguigu.ssh.entities.Department;
     6 
     7 public class DepartmentDao extends BaseDao{
     8 
     9     //获取查询到的Department集合
    10     public List<Department> getAll(){
    11         String hql="FROM Department";
    12         return getSession().createQuery(hql).list();
    13     }
    14 }
    View Code

      (2)com.atguigu.ssh.service包中:新建DepartmentService类:DepartmentService.java 

      
     1 package com.atguigu.ssh.service;
     2 
     3 import java.util.List;
     4 
     5 import com.atguigu.ssh.dao.DepartmentDao;
     6 import com.atguigu.ssh.entities.Department;
     7 
     8 public class DepartmentService {
     9 
    10     private DepartmentDao departmentDao;
    11     public void setDepartmentDao(DepartmentDao departmentDao) {
    12         this.departmentDao = departmentDao;
    13     }
    14     
    15     public List<Department> getAll(){
    16         return departmentDao.getAll();
    17     }
    18 }
    View Code

      (3) com.atguigu.ssh.actions包下的EmployeeAction.java:填写获取Department集合的方法并且放入request中(jsp页面中就可以通过request直接获取)

      
     1 //3-1  查询Department
     2     private DepartmentService departmentService;
     3     public void setDepartmentService(DepartmentService departmentService) {
     4         this.departmentService = departmentService;
     5     }
     6     //3-2 实现添加员工信息的方法
     7     public String input(){
     8         request.put("departments", departmentService.getAll());
     9         return INPUT;
    10     }
    View Code

    3  完善applicationContext-beans.xml 

      
     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <beans xmlns="http://www.springframework.org/schema/beans"
     3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     4     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
     5     
     6     <bean id="employeeDao" class="com.atguigu.ssh.dao.EmployeeDao">
     7         <property name="sessionFactory" ref="sessionFactory"></property>
     8     </bean>
     9     
    10     <bean id="departmentDao" class="com.atguigu.ssh.dao.DepartmentDao">
    11         <property name="sessionFactory" ref="sessionFactory"></property>
    12     </bean>
    13     
    14     <bean id="employeeService" class="com.atguigu.ssh.service.EmployeeService">
    15         <property name="employeeDao" ref="employeeDao"></property>
    16     </bean>
    17     
    18     <bean id="departmentService" class="com.atguigu.ssh.service.DepartmentService">
    19         <property name="departmentDao" ref="departmentDao"></property>
    20     </bean>
    21     
    22     <bean id="employeeAction" class="com.atguigu.ssh.actions.EmployeeAction"
    23           scope="prototype">
    24         <property name="employeeService" ref="employeeService"></property>
    25         <property name="departmentService" ref="departmentService"></property>
    26     </bean>
    27 </beans>
    View Code

    4 完善struts.xml,添加显示添加页面语句:<result name="input">/WEB-INF/views/emp-input.jsp</result>

    5  WebContent-WEB-INF-views下新建emp-input.jsp 

      
     1 <%@ page language="java" contentType="text/html; charset=UTF-8"
     2     pageEncoding="UTF-8"%>
     3 <%@ taglib prefix="s" uri="/struts-tags" %>    
     4 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
     5 <html>
     6 <head>
     7 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
     8 <title>Insert title here</title>
     9 </head>
    10 <body>
    11     <h4>Employee Input Page</h4>
    12     
    13     <s:form action="emp-save" method="post">
    14         <s:textfield name="lastName" label="LastName"></s:textfield>
    15         <s:textfield name="email" label="Email"></s:textfield>
    16         <s:textfield name="birth" label="Birth"></s:textfield>
    17         
    18         <s:select list="#request.departments"
    19                   listKey="id" listValue="departmentName" name="department.id"
    20                   label="Department"></s:select>
    21         <s:submit></s:submit>                  
    22     </s:form>
    23     
    24 </body>
    25 </html>
    View Code

     二、

    1 实现ModelDriven拦截器操作

       (1)EmployeeAction实现ModelDriven<Employee>,Preparable接口,添加实现方法: 

     1 //****
     2     @Override
     3     public void prepare() throws Exception {
     4     }
     5     //****
     6     private Employee model;
     7     //****
     8     @Override
     9     public Employee getModel() {
    10         return model;
    11     }
    12 //**** 4 使用ModelDriven拦截器方法存储添加的信息
    13     public String save(){
    14         System.out.println(model);
    15         model.setCreateTime(new Date());
    16                   employeeService.saveorUpdate(model);
    17         return SUCCESS;
    18     }
    19     //****
    20     public void prepareSave(){
    21         model=new Employee();
    22     }
    23 
    24 //**** 拦截器的方法
    25     public void prepareInput(){
    26         
    27     }
    View Code

      (2)Struts.xml配置下拦截器: 

     1 <!-- 定义新的拦截器栈, 
     2             配置 prepare 拦截器栈的 alwaysInvokePrepare 参数值为 false -->
     3         <interceptors>
     4             <interceptor-stack name="sshStack">
     5                 <interceptor-ref name="paramsPrepareParamsStack">
     6                     <param name="prepare.alwaysInvokePrepare">false</param>
     7                 </interceptor-ref>
     8             </interceptor-stack>
     9         </interceptors>
    10         <!-- 使用新的拦截器栈 -->
    11         <default-interceptor-ref name="sshStack"></default-interceptor-ref>
    View Code

    2 定制类型转换器:使输入的Birth字符串转化为Date类型

      (1)新建包com.atguigu.ssh.converters:新建SSHDateConverter.java类     

      
     1 package com.atguigu.ssh.converters;
     2 
     3 import java.text.DateFormat;
     4 import java.text.ParseException;
     5 import java.text.SimpleDateFormat;
     6 import java.util.Date;
     7 import java.util.Map;
     8 
     9 import org.apache.struts2.util.StrutsTypeConverter;
    10 
    11 public class SSHDateConverter extends StrutsTypeConverter {
    12 
    13     private DateFormat dateFormat;
    14     
    15     public SSHDateConverter()
    16     {
    17         dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    18     }
    19     
    20     @Override
    21     public Object convertFromString(Map context, String[] values, Class toClass) {
    22         if(toClass == Date.class){
    23             if(values !=null && values.length>0){
    24                 String value=values[0];
    25                 try {
    26                     return dateFormat.parse(value);
    27                 } catch (ParseException e) {
    28                     e.printStackTrace();
    29                 }
    30             }
    31         }
    32         return values;
    33     }
    34 
    35     @Override
    36     public String convertToString(Map context, Object o) {
    37         if(o instanceof Date){
    38             Date date=(Date)o;
    39             return dateFormat.format(date);
    40         }
    41         return null;
    42     }
    43 
    44 }
    View Code

      (2)src-cong下新建xwork-conversion.properties,配置类型转换器:

      java.util.Date=com.atguigu.ssh.converters.SSHDateConverter

    3 实现存储操作:

      (1)EmployeeDao.java中添加save方法: 

    1 //3 添加、存储
    2     public void saveOrUpadate(Employee employee){
    3         getSession().saveOrUpdate(employee);
    4     }
    View Code

      (2)EmployeeService.java

    1 //3 添加、存储
    2     public void saveorUpdate(Employee employee){
    3         employeeDao.saveOrUpadate(employee);
    4     }
    View Code

      (3)EmployeeAction.java: 

     1 //**** 4 使用ModelDriven拦截器方法存储添加的信息
     2     public String save(){
     3         System.out.println(model);
     4         model.setCreateTime(new Date());
     5         employeeService.saveorUpdate(model);
     6         return SUCCESS;
     7     }
     8     //****
     9     public void prepareSave(){
    10         model=new Employee();
    11     }
    View Code

    4 显示页面:格式化时间操作:

    1 <td>
    2                         <s:date name="birth" format="yyyy-MM-dd"/>
    3                     </td>
    4                     <td>
    5                         <s:date name="createTime" format="yyyy-MM-dd hh:mm:ss"/>
    6                     </td>
    View Code

    结构图:

      

    文件:

    1 EmployeeAction.java 

      1 package com.atguigu.ssh.actions;
      2 
      3 import java.io.ByteArrayInputStream;
      4 import java.io.InputStream;
      5 import java.io.UnsupportedEncodingException;
      6 import java.util.Date;
      7 import java.util.Map;
      8 
      9 import org.apache.struts2.interceptor.RequestAware;
     10 
     11 import com.atguigu.ssh.entities.Employee;
     12 import com.atguigu.ssh.service.DepartmentService;
     13 import com.atguigu.ssh.service.EmployeeService;
     14 import com.opensymphony.xwork2.ActionSupport;
     15 import com.opensymphony.xwork2.ModelDriven;
     16 import com.opensymphony.xwork2.Preparable;
     17 
     18 public class EmployeeAction extends ActionSupport implements RequestAware,
     19 ModelDriven<Employee>,Preparable{
     20     
     21     private static final long serialVersionUID = 1L;
     22     
     23     private EmployeeService employeeService;
     24     
     25     public void setEmployeeService(EmployeeService employeeService){
     26         this.employeeService=employeeService;
     27     }
     28     
     29     //**** 4 使用ModelDriven拦截器方法存储添加的信息
     30     public String save(){
     31         System.out.println(model);
     32         model.setCreateTime(new Date());
     33         employeeService.saveorUpdate(model);
     34         return SUCCESS;
     35     }
     36     //****
     37     public void prepareSave(){
     38         model=new Employee();
     39     }
     40     
     41     //3-1  查询Department
     42     private DepartmentService departmentService;
     43     public void setDepartmentService(DepartmentService departmentService) {
     44         this.departmentService = departmentService;
     45     }
     46     //3-2 实现添加员工信息的方法
     47     public String input(){
     48         request.put("departments", departmentService.getAll());
     49         return INPUT;
     50     }
     51     
     52     //**** 拦截器的方法
     53     public void prepareInput(){
     54         
     55     }
     56     
     57     //2 删除
     58     private Integer id;
     59     public void setId(Integer id) {
     60         this.id = id;
     61     }
     62     /*public String delete(){
     63         employeeService.delete(id);
     64         return SUCCESS;
     65     }*/
     66     //2-1 使用Ajax方式删除
     67     private InputStream inputStream;
     68     
     69     public InputStream getInputStream() {
     70         return inputStream;
     71     }
     72     
     73     public String delete(){
     74         employeeService.delete(id);
     75         try {
     76             //删除成功
     77             inputStream=new ByteArrayInputStream("1".getBytes("UTF-8"));
     78         } catch (UnsupportedEncodingException e) {
     79             //删除失败
     80             try {
     81                 inputStream=new ByteArrayInputStream("0".getBytes("UTF-8"));
     82             } catch (UnsupportedEncodingException e1) {
     83                 // TODO Auto-generated catch block
     84                 e1.printStackTrace();
     85             }
     86             e.printStackTrace();
     87         }
     88         return "ajax-delete-success";
     89     }
     90     //1 查询
     91     public String list(){
     92         request.put("employees", employeeService.getAll()); 
     93         return "list";
     94     }
     95 
     96     //放到页面里
     97     private Map<String,Object> request;
     98     
     99     @Override
    100     public void setRequest(Map<String, Object> arg0) {
    101         this.request=arg0;
    102     }
    103     
    104     //****
    105     @Override
    106     public void prepare() throws Exception {
    107     }
    108     //****
    109     private Employee model;
    110     //****
    111     @Override
    112     public Employee getModel() {
    113         return model;
    114     }
    115 
    116 }
    View Code

    2 struts.xml

     1 <?xml version="1.0" encoding="UTF-8" ?>
     2 <!DOCTYPE struts PUBLIC
     3     "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
     4     "http://struts.apache.org/dtds/struts-2.3.dtd">
     5 
     6 <struts>
     7 
     8     <constant name="struts.enable.DynamicMethodInvocation" value="false" />
     9     <constant name="struts.devMode" value="true" />
    10 
    11     <package name="default" namespace="/" extends="struts-default">
    12         <!-- 定义新的拦截器栈, 
    13             配置 prepare 拦截器栈的 alwaysInvokePrepare 参数值为 false -->
    14         <interceptors>
    15             <interceptor-stack name="sshStack">
    16                 <interceptor-ref name="paramsPrepareParamsStack">
    17                     <param name="prepare.alwaysInvokePrepare">false</param>
    18                 </interceptor-ref>
    19             </interceptor-stack>
    20         </interceptors>
    21         <!-- 使用新的拦截器栈 -->
    22         <default-interceptor-ref name="sshStack"></default-interceptor-ref>
    23         
    24         <action name="emp-*" class="employeeAction"
    25                 method="{1}">
    26                 <result name="list">/WEB-INF/views/emp-list.jsp</result>
    27                 
    28                 <result type="stream" name="ajax-delete-success">
    29                     <param name="contentType">text/html</param>
    30                     <param name="inputName">inputStream</param>
    31                    </result>
    32                    <result name="input">/WEB-INF/views/emp-input.jsp</result>
    33                    
    34                    <result name="success" type="redirect">/emp-list</result>     
    35         </action>
    36     </package>
    37 
    38 </struts>
    View Code

    3 emp-list.jsp

     1 <%@ page language="java" contentType="text/html; charset=UTF-8"
     2     pageEncoding="UTF-8"%>
     3 <%@ taglib prefix="s" uri="/struts-tags" %>   
     4 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
     5 <html>
     6 <head>
     7 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
     8 <title>Insert title here</title>
     9 <script type="text/javascript" SRC="scripts/jquery-1.7.2.js"></script>
    10 <script type="text/javascript">
    11     //删除, 使用 ajax 的方式
    12     $(function(){
    13         $(".delete").click(function(){
    14             var lastName=$(this).next(":input").val();
    15             var flag=confirm("是否要删除"+lastName+"的信息吗?");
    16             //确认删除, 使用 ajax 的方式
    17             if(flag){
    18                 //获取要删除的行
    19                 var $tr=$(this).parent().parent();
    20                 var url=this.href;
    21                 var args={"time":new Date()};
    22                 $.post(url,args,function(data){
    23                     //若 data 的返回值为 1, 则提示 删除成功, 且把当前行删除
    24                     if(data==1){
    25                         alert("删除成功!");
    26                         $tr.remove();
    27                     }else{
    28                         //若 data 的返回值不是 1, 提示删除失败. 
    29                         alert("删除失败!");
    30                     }
    31                 });
    32             }
    33             return false;
    34         });
    35     })
    36 </script>
    37 </head>
    38 <body>
    39     <h3>Employee List Page</h3>
    40     
    41     <s:if test="#request.employees == null ||#request.size()==0">
    42         没有员工信息
    43     </s:if>
    44     <s:else>
    45         <table border="1" cellpadding="10" cellspacing="0">
    46             <tr>
    47                 <td>ID</td>
    48                 <td>LASTNAME</td>
    49                 <td>EMAIL</td>
    50                 <td>BIRTH</td>
    51                 <td>CREATETIME</td>
    52                 <td>DEPT</td>
    53             </tr>
    54             <s:iterator value="#request.employees">
    55                 <tr>
    56                     <td>${id}</td>
    57                     <td>${lastName}</td>
    58                     <td>${email }</td>
    59                     <%-- 
    60                         <td>${birth}</td>
    61                         <td>${createTime}</td>
    62                      --%>
    63                     <td>
    64                         <s:date name="birth" format="yyyy-MM-dd"/>
    65                     </td>
    66                     <td>
    67                         <s:date name="createTime" format="yyyy-MM-dd hh:mm:ss"/>
    68                     </td>
    69                     
    70                     <td>${department.departmentName}</td>
    71                     <td>
    72                         <a href="emp-delete?id=${id }" class="delete">Delete</a>
    73                         <input type="hidden" value="${lastName}"/>
    74                     </td>
    75                 </tr>
    76             </s:iterator>
    77         </table>
    78     </s:else>
    79 </body>
    80 </html>
    View Code

    4 emp-input.jsp 

     1 <%@ page language="java" contentType="text/html; charset=UTF-8"
     2     pageEncoding="UTF-8"%>
     3 <%@ taglib prefix="s" uri="/struts-tags" %>    
     4 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
     5 <html>
     6 <head>
     7 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
     8 <title>Insert title here</title>
     9 </head>
    10 <body>
    11     <h4>Employee Input Page</h4>
    12     
    13     <s:form action="emp-save" method="post">
    14         <s:textfield name="lastName" label="LastName"></s:textfield>
    15         <s:textfield name="email" label="Email"></s:textfield>
    16         <s:textfield name="birth" label="Birth"></s:textfield>
    17         
    18         <s:select list="#request.departments"
    19                   listKey="id" listValue="departmentName" name="department.id"
    20                   label="Department"></s:select>
    21         <s:submit></s:submit>                  
    22     </s:form>
    23     
    24 </body>
    25 </html>
    View Code

      

      

        

  • 相关阅读:
    [实战]MVC5+EF6+MySql企业网盘实战(11)——新建文件夹2
    [实战]MVC5+EF6+MySql企业网盘实战(10)——新建文件夹
    FMXUI
    x-superobject
    mORMot
    NativeXml
    superobject
    jsondataobjects
    QDAC
    DIOCP
  • 原文地址:https://www.cnblogs.com/noaman/p/5885458.html
Copyright © 2020-2023  润新知