• SSH(Struts 2.3.31 + Spring 4.1.6 + Hibernate 5.0.12 + Ajax)框架整合实现简单的增删改查(包含分页,Ajax 无刷新验证该用户是否存在)


    软件152 余建强

    该文将以员工、部门两表带领大家进入SSH的整合教程:

    源码下载:http://download.csdn.net/detail/qq_35318576/9877235

    SSH 整合 jar 包下载:http://download.csdn.net/detail/qq_35318576/9874435

    1.建立数据库命名为 ssh,建立项目命名为 SSH。(具体命名以实际为准,数据库表将会以 Hibernate 建表语句自动生成)

    2.在项目 SSH 中的 lib 目录导入相应的 jar 包,我导入的 jar 包如下:

    3.该码农项目目录结构以及显示界面如下(注:com.cqvie.converters 包无用,com.cqvie.util 包属于分页工具,具体使用详见我的下一条博客):

    4.在包 com.cqvie.model 中创建实体类 Employee.java 和 Department.java

    package com.cqvie.model;
    
    import java.util.Date;
    
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.Id;
    import javax.persistence.ManyToOne;
    
    import org.hibernate.annotations.GenericGenerator;
    
    @Entity
    public class Employee {
    
        private String e_uuid;    //员工的主键 UUID
        private String e_name;    //姓名
        private String e_pwd;    //密码
        private String e_email;    //邮箱
        private Date e_birthday;    //生日
        private Date e_createDate;    //创建日期
        private Department e_department;    //部门
        
        @Id
        @GeneratedValue(generator = "uuid")
        @GenericGenerator(name = "uuid", strategy = "uuid")
        public String getE_uuid() {
            return e_uuid;
        }
        public void setE_uuid(String e_uuid) {
            this.e_uuid = e_uuid;
        }
        public String getE_name() {
            return e_name;
        }
        public void setE_name(String e_name) {
            this.e_name = e_name;
        }
        public String getE_pwd() {
            return e_pwd;
        }
        public void setE_pwd(String e_pwd) {
            this.e_pwd = e_pwd;
        }
        public String getE_email() {
            return e_email;
        }
        public void setE_email(String e_email) {
            this.e_email = e_email;
        }
        public Date getE_birthday() {
            return e_birthday;
        }
        public void setE_birthday(Date e_birthday) {
            this.e_birthday = e_birthday;
        }
        public Date getE_createDate() {
            return e_createDate;
        }
        public void setE_createDate(Date e_createDate) {
            this.e_createDate = e_createDate;
        }
        @ManyToOne
        public Department getE_department() {
            return e_department;
        }
        public void setE_department(Department e_department) {
            this.e_department = e_department;
        }
        
    //    @Override
    //    public String toString() {
    //        return "[e_uuid=" + e_uuid + ",e_name=" + e_name + ",e_pwd" + e_pwd 
    //                + ",e_email=" + e_email + ",e_birthday" + e_birthday 
    //                + ",e_createDate" + e_createDate + ",e_department" + e_department.getD_uuid() + "]";
    //    }
    }
    Employee.java
    package com.cqvie.model;
    
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.Id;
    
    import org.hibernate.annotations.GenericGenerator;
    
    @Entity
    public class Department {
    
        private String d_uuid;    //部门的主键 UUID
        private String d_name;    //部门名
        
        @Id
        @GeneratedValue(generator = "uuid")
        @GenericGenerator(name = "uuid", strategy = "uuid")
        public String getD_uuid() {
            return d_uuid;
        }
        public void setD_uuid(String d_uuid) {
            this.d_uuid = d_uuid;
        }
        public String getD_name() {
            return d_name;
        }
        public void setD_name(String d_name) {
            this.d_name = d_name;
        }
    }
    Department.java

    5.Spring + Hibernate 整合:

    配置 jdbc.properties 文件信息连接数据库:

    jdbc.driverClassName=com.mysql.jdbc.Driver
    jdbc.url=jdbc:mysql://localhost:3306/spring
    jdbc.username=root
    jdbc.password=123
    jdbc.properties

    配置 Spring 配置文件 applicationContext.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"
         xmlns:context="http://www.springframework.org/schema/context"
         xmlns:aop="http://www.springframework.org/schema/aop"
         xmlns:tx="http://www.springframework.org/schema/tx"
         xsi:schemaLocation="http://www.springframework.org/schema/beans
             http://www.springframework.org/schema/beans/spring-beans.xsd
             http://www.springframework.org/schema/context
             http://www.springframework.org/schema/context/spring-context.xsd
             http://www.springframework.org/schema/aop 
             http://www.springframework.org/schema/aop/spring-aop.xsd
             http://www.springframework.org/schema/tx
             http://www.springframework.org/schema/tx/spring-tx.xsd">
        
        <!-- 向容器注册注解方式 -->     
        <context:annotation-config />
        
        <!-- 自动扫描包 -->
        <context:component-scan base-package="com.cqvie" />
        
        <!-- 导入 .properties 资源配置文件 -->
        <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
            <property name="locations" value="classpath:jdbc.properties" />
        </bean>
        
        <!-- 配置数据源 dataSource -->
        <bean id="dataSource" destroy-method="close" class="org.apache.commons.dbcp2.BasicDataSource">
            <property name="driverClassName" value="${jdbc.driverClassName}" />
            <property name="url" value="${jdbc.url}" />
            <property name="username" value="${jdbc.username}" />
            <property name="password" value="${jdbc.password}" />
        </bean>
        
        <!-- 配置 sessionFactory -->
        <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
            <property name="dataSource" ref="dataSource" />
            <!-- 扫描包下面的java文件 -->
            <property name="packagesToScan">
                <list>
                    <value>com.cqvie.model</value>
                </list>
            </property>
            <!-- 配置 hibernate.cfg.xml 中的信息 -->
            <property name="hibernateProperties">
                <props>
                      <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                      <prop key="hibernate.show_sql">true</prop>
                      <prop key="hibernate.format_sql">true</prop>
                      <prop key="hibernate.hbm2ddl.auto">update</prop>
                </props>
            </property>
        </bean>
        
        <!-- 配置 Spring 的声明式事务 -->
        <!-- 事务管理器 -->
        <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <property name="dataSource" ref="dataSource"/>
        </bean>
     
         <!-- 注解方式
            <tx:annotation-driven transaction-manager="txManager"/>
         -->
         <!-- XML方式   -->
         <aop:config>
             <aop:pointcut expression="execution(public * com.cqvie.service..*.*(..))" id="bussinessService"/>
             <aop:advisor pointcut-ref="bussinessService" advice-ref="txAdvice"/>
         </aop:config>
         
         <tx:advice id="txAdvice" transaction-manager="txManager">
             <tx:attributes>
                 <tx:method name="get*" read-only="true"/>
                 <tx:method name="*" propagation="REQUIRED"/>
             </tx:attributes>
         </tx:advice>
         
    <!-- ************************************************************************************************ -->
         <!-- Spring 调用 Hibernate 的持久化操作 -->
         <bean id="hibernateTemplate" class="org.springframework.orm.hibernate4.HibernateTemplate">
             <property name="sessionFactory" ref="sessionFactory"></property>
         </bean>
    
    </beans>
    applicationContext.xml

    配置日志文件 log4j2.xml,防止报错以及打印输出日志信息:

    <?xml version="1.0" encoding="UTF-8"?>
    <Configuration>
        <Appenders>
            <Console name="STDOUT" target="SYSTEM_OUT">
                <PatternLayout pattern="%d %-5p [%t] %C{2} (%F:%L) - %m%n"/>
            </Console>
        </Appenders>
        <Loggers>
            <Logger name="com.opensymphony.xwork2" level="debug"/>
            <Logger name="org.apache.struts2" level="debug"/>
            <Root level="warn">
                <AppenderRef ref="STDOUT"/>
            </Root>
        </Loggers>
    </Configuration>
    log4j2.xml

    6.在包 com.cqvie.dao 中建立两个 Dao 的实现接口类 DepartmentDao.java 和 EmployeeDao.java:

    package com.cqvie.dao;
    
    import java.util.List;
    
    import com.cqvie.model.Department;
    
    public interface DepartmentDao {
    
        public Department loadByUUID(String uuid);    //根据 UUID 查询该部门信息
        public String selectByName(String name);    //根据部门名称查询该部门信息
        public List<Department> getAllDepartment();    //获得全部部门信息
        
    }
    DepartmentDao.java
    package com.cqvie.dao;
    
    import java.util.List;
    
    import com.cqvie.model.Employee;
    
    public interface EmployeeDao {
    
        public boolean isExists(String username, String password);    //验证用户是否存在
        public void saveOrUpdateEmployee(Employee employee);    //更新或者保存用户
        public List<Employee> getAllEmployee();        //获得所有的用户信息
        public int getEmployeeByName(String name);        //根据员工姓名查询该员工信息
        public void deleteEmployee(Employee employee);        //删除员工信息
        public Employee getEmployee(String uuid);        //根据 UUID 获得该员工的信息
        
        /**   
         * 分页查询   
         * @param currentPage  当前页
         * @param pageSize  每页显示的条数   
         * @return 查询的记录集合   
         */    
        public List<Employee> queryForPage(int currentPage, int pageSize); 
        
    }
    EmployeeDao.java

    7.Dao 包中的接口类的实现类 DepartmentDaoImpl.java 和 EmployeeDaoImpl.java:

    package com.cqvie.dao.impl;
    
    import java.util.List;
    
    import javax.annotation.Resource;
    
    import org.springframework.orm.hibernate4.HibernateTemplate;
    import org.springframework.stereotype.Component;
    
    import com.cqvie.dao.DepartmentDao;
    import com.cqvie.model.Department;
    
    @Component("departmentDao")
    public class DepartmentDaoImpl implements DepartmentDao {
    
        private HibernateTemplate hibernateTemplate;
        
        public HibernateTemplate getHibernateTemplate() {
            return hibernateTemplate;
        }
        @Resource
        public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
            this.hibernateTemplate = hibernateTemplate;
        }
        
        /**
         * 根据主键 UUID 查询信息
         */
        @Override
        public Department loadByUUID(String uuid) {
            return this.hibernateTemplate.load(Department.class, uuid);
        }
        
        /**
         * 根据 部门名称 查询信息
         */
        @SuppressWarnings("unchecked")
        @Override
        public String selectByName(String name) {
            String hql = "select d_uuid from Department where d_name=?";
            Object[] parmas = new Object[]{name};
            List<String> list = (List<String>) hibernateTemplate.find(hql, parmas);
            return list.get(0);
        }
        
        /**
         * 获取所有部门
         */
        @SuppressWarnings("unchecked")
        @Override
        public List<Department> getAllDepartment() {
            String hql = "from Department";
            List<Department> departments = (List<Department>) hibernateTemplate.find(hql);
            return departments;
        }
    
    }
    DepartmentDaoImpl.java
    package com.cqvie.dao.impl;
    
    import java.util.List;
    
    import javax.annotation.Resource;
    
    import org.hibernate.Session;
    import org.springframework.orm.hibernate4.HibernateCallback;
    import org.springframework.orm.hibernate4.HibernateTemplate;
    import org.springframework.stereotype.Component;
    
    import com.cqvie.dao.EmployeeDao;
    import com.cqvie.model.Employee;
    import com.cqvie.util.PageHibernateCallback;
    
    @Component("employeeDao")
    public class EmployeeDaoImpl implements EmployeeDao {
    
        private HibernateTemplate hibernateTemplate;
        
        public HibernateTemplate getHibernateTemplate() {
            return hibernateTemplate;
        }
        @Resource
        public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
            this.hibernateTemplate = hibernateTemplate;
        }
    
        /**
         * 判断该用户是否存在
         */
        @SuppressWarnings("unchecked")
        @Override
        public boolean isExists(String username, String password) {
            String hql = "from Employee where e_name=? and e_pwd=?";
            Object[] params = new Object[]{username, password};
            List<Employee> emp = (List<Employee>) hibernateTemplate.find(hql, params);
            if(emp != null && emp.size() > 0)
                return true;
            return false;
        }
        
        /**
         * 保存一个用户
         */
        @Override
        public void saveOrUpdateEmployee(Employee employee) {
            //this.hibernateTemplate.saveOrUpdate(employee);
            Session session = hibernateTemplate.getSessionFactory().openSession();
            session.saveOrUpdate(employee);
            session.flush();
            session.refresh(employee); 
        }
        
        /**
         * 获得全部用户
         */
        @SuppressWarnings("unchecked")
        @Override
        public List<Employee> getAllEmployee() {
            String hql = "from Employee";
            List<Employee> employees = (List<Employee>) hibernateTemplate.find(hql);
            return employees;
        }
        
        /**
         * 根据员工姓名查询该员工信息
         */
        @SuppressWarnings("unchecked")
        @Override
        public int getEmployeeByName(String name) {
            String hql = "select e_uuid from Employee where e_name=?";
            Object[] parmas = new Object[]{name};
            List<String> list = (List<String>) hibernateTemplate.find(hql, parmas);
            return list.size();
        }
        
        /**
         * 删除员工信息
         */
        @Override
        public void deleteEmployee(Employee employee) {
            hibernateTemplate.delete(employee);
        }
        
        /**
         * 根据 UUID 获得该员工的信息
         */
        @Override
        public Employee getEmployee(String uuid) {
            return hibernateTemplate.get(Employee.class, uuid);
        }
        
        /**
         * 分页查询
         */
        @SuppressWarnings({ "unchecked", "rawtypes" })
        @Override
        public List<Employee> queryForPage(int currentPage, int pageSize) {
            String hql = "from Employee";
            List<Employee> list = (List<Employee>) this.hibernateTemplate.execute( (HibernateCallback<Employee>) new PageHibernateCallback(hql, new Object[] {}, currentPage, pageSize));
            if(list != null && list.size() > 0) {
                return list;
            }
            return null;
        }
        
    
    }
    EmployeeDaoImpl.java

    8.在包 com.cqvie.service 中建立两个 Service 的实现接口类 DepartmentService.java 和 EmployeeService.java:

    package com.cqvie.service;
    
    import java.util.List;
    
    import com.cqvie.model.Department;
    
    public interface DepartmentService {
    
        public Department loadByUUID(String uuid);    //根据 UUID 查询该部门信息
        public String selectByName(String name);    //根据部门名称查询该部门信息
        public List<Department> getAllDepartment();    //获得全部部门信息
        
    }
    DepartmentService.java
    package com.cqvie.service;
    
    import java.util.List;
    
    import com.cqvie.model.Employee;
    import com.cqvie.util.PageBean;
    
    public interface EmployeeService {
    
        public boolean isExists(Employee employee);    //验证用户是否存在
        public void saveOrUpdateEmployee(Employee employee);    //更新或者保存用户
        public List<Employee> getAllEmployee();    //获得所有的用户信息
        public boolean getEmployeeByName(String name);    //根据员工姓名查询该员工信息
        public void deleteEmployee(Employee employee);    //删除员工信息
        public Employee getEmployee(String uuid);    //根据 UUID 获得该员工的信息
        
        public PageBean queryForPage(int pageSize,int currentPage);    //分页显示数据
    }
    EmployeeService.java

    9.Service 包中的接口类的实现类 DepartmentServiceImpl.java 和 EmployeeServiceImpl.java:

    package com.cqvie.service.impl;
    
    import java.util.List;
    
    import javax.annotation.Resource;
    
    import org.springframework.stereotype.Component;
    
    import com.cqvie.dao.DepartmentDao;
    import com.cqvie.model.Department;
    import com.cqvie.service.DepartmentService;
    
    @Component("departmentService")
    public class DepartmentServiceImpl implements DepartmentService {
    
        private DepartmentDao departmentDao;
    
        public DepartmentDao getDepartmentDao() {
            return departmentDao;
        }
        @Resource
        public void setDepartmentDao(DepartmentDao departmentDao) {
            this.departmentDao = departmentDao;
        }
        
        /**
         * 根据 UUID 查询该部门信息
         */
        @Override
        public Department loadByUUID(String uuid) {
            return this.departmentDao.loadByUUID(uuid);
        }
        
        /**
         * 根据部门名称查询该部门信息
         */
        @Override
        public String selectByName(String name) {
            return this.departmentDao.selectByName(name);
        }
        
        /**
         * 获得全部部门信息
         */
        @Override
        public List<Department> getAllDepartment() {
            return this.departmentDao.getAllDepartment();
        }
        
    }
    DepartmentServiceImpl.java
    package com.cqvie.service.impl;
    
    import java.util.List;
    
    import javax.annotation.Resource;
    
    import org.springframework.stereotype.Component;
    
    import com.cqvie.dao.EmployeeDao;
    import com.cqvie.model.Employee;
    import com.cqvie.service.EmployeeService;
    import com.cqvie.util.PageBean;
    
    @Component("employeeService")
    public class EmployeeServiceImpl implements EmployeeService {
    
        private EmployeeDao employeeDao;
        
        public EmployeeDao getEmployeeDao() {
            return employeeDao;
        }
        @Resource
        public void setEmployeeDao(EmployeeDao employeeDao) {
            this.employeeDao = employeeDao;
        }
    
        /**
         * 验证用户是否存在
         */
        @Override
        public boolean isExists(Employee employee) {
            boolean result = employeeDao.isExists(employee.getE_name(), employee.getE_pwd());
            return result;
        }
        
        /**
         * 更新或者保存用户
         */
        @Override
        public void saveOrUpdateEmployee(Employee employee) {
            employeeDao.saveOrUpdateEmployee(employee);
        }
        
        /**
         * 获得所有的用户信息
         */
        @Override
        public List<Employee> getAllEmployee() {
            return this.employeeDao.getAllEmployee();
        }
        
        /**
         * 根据员工姓名查询该员工信息
         */
        @Override
        public boolean getEmployeeByName(String name) {
            return this.employeeDao.getEmployeeByName(name) > 0;
        }
        
        /**
         * 删除员工信息
         */
        @Override
        public void deleteEmployee(Employee employee) {
            employeeDao.deleteEmployee(employee);
        }
        
        /**
         * 根据 UUID 获得该员工的信息
         */
        @Override
        public Employee getEmployee(String uuid) {
            return employeeDao.getEmployee(uuid);
        }
        
        /**
         * 分页查询
         */
        @Override
        public PageBean queryForPage(int pageSize, int page) {
            
            int allRow = employeeDao.getAllEmployee().size();//memberDao.getAllRowCount(hql);    //总记录数   
            int totalPage = PageBean.countTotalPage(pageSize, allRow);    //总页数   
            final int offset = PageBean.countOffset(pageSize, page);    //当前页开始记录   
            final int length = pageSize;    //每页记录数   
            final int currentPage = PageBean.countCurrentPage(page);   
            List<Employee> list = employeeDao.queryForPage(offset, length);    //"一页"的记录   
    
            //把分页信息保存到Bean中   
            PageBean pageBean = new PageBean();   
            pageBean.setPageSize(pageSize);
            pageBean.setCurrentPage(currentPage);   
            pageBean.setAllRow(allRow);   
            pageBean.setTotalPage(totalPage);   
            pageBean.setList(list);   
            pageBean.init(); 
            
            return pageBean;   
        }
        
    }
    EmployeeServiceImpl.java

    10.搭建 Struts2,配置 Struts2 的 xml 配置文件 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.devMode" value="true" />
        
        <!-- 在 URL 地址中动态指定(动态方法调用DMI) -->
        <constant name="struts.enable.DynamicMethodInvocation" value="true" />
        
        <!-- 解决中文乱码问题 -->
        <constant name="struts.i18n.encoding" value="UTF-8" />
        
         <package name="login" namespace="/" extends="struts-default">
             
             <action name="login" class="loginAction">
                 <result name="success" type="redirect">emp-page</result>
                 <result name="error">/login.jsp</result>
             </action>
             
             <action name="emp-*" class="employeeAction" method="{1}">
                 <result name="list">/index.jsp</result>
                 <result name="page">/index_page.jsp</result>
                 <result name="input" >/emp-add.jsp</result>
                 <result name="success" type="redirect">emp-page</result>
                 <result name="delete" type="redirect">emp-page</result>
                 <result name="update" >/emp-add.jsp</result>
                 <result name="ajax-success" type="stream">
                     <param name="contentType">text/html</param>
                     <param name="inputName">inputStream</param>
                 </result>
             </action>
             
         </package>
         
    </struts>
    struts.xml

    11.配置 WEB 项目的配置文件 web.xml:

    <?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" 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>SSH_Demo</display-name>
      <welcome-file-list>
        <welcome-file>login.jsp</welcome-file>
      </welcome-file-list>
      <!-- 加载 Spring 的配置文件 -->
      <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
      </listener>
      <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
      </context-param>
      <!-- Spring 防止中文乱码 -->
      <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
          <param-name>encoding</param-name>
          <param-value>UTF-8</param-value>
        </init-param>
      </filter>
      <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
      </filter-mapping>
      <!-- 扩大 Session 的取值范围 -->
      <filter>
        <filter-name>openSessionInView</filter-name>
        <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
        <init-param>
          <param-name>sessionFactoryBeanName</param-name>
          <param-value>sessionFactory</param-value>
        </init-param>
      </filter>
      <filter-mapping>
        <filter-name>openSessionInView</filter-name>
        <url-pattern>/*</url-pattern>
      </filter-mapping>
      <!-- 加载 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>
    </web-app>
    web.xml

    12.功能的实现一,用户登录:

    用户登录界面的编写 login.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>用户登录</title>
    </head>
    <body>
        <form action="login" method="post">
            <h1>用户登录</h1>    <hr>
            <input type="text" name="username" />    <br><br>
            <input type="password" name="password" />    <br><br>
            <input type="submit" value="登录" />
            <input type="reset" value="重置" />
        </form> 
        
        <s:debug></s:debug>
    </body>
    </html>
    login.jsp

    Struts2 实现登录验证类 LoginAction.java:

    package com.cqvie.action;
    
    import java.util.Map;
    
    import javax.annotation.Resource;
    
    import org.apache.struts2.interceptor.ApplicationAware;
    import org.springframework.context.annotation.Scope;
    import org.springframework.stereotype.Component;
    
    import com.cqvie.model.Employee;
    import com.cqvie.service.EmployeeService;
    import com.cqvie.vo.LoginInfo;
    import com.opensymphony.xwork2.ActionSupport;
    import com.opensymphony.xwork2.ModelDriven;
    
    @Component("loginAction")
    @Scope("prototype")
    public class LoginAction extends ActionSupport implements ModelDriven<LoginInfo>, ApplicationAware {
    
        private static final long serialVersionUID = 1L;
        
        private Map<String, Object> application;
        private LoginInfo loginInfo = new LoginInfo();
        private EmployeeService employeeService;
    
        public Map<String, Object> getApplication() {
            return application;
        }
        public void setApplication(Map<String, Object> application) {
            this.application = application;
        }
        public LoginInfo getLoginInfo() {
            return loginInfo;
        }
        public void setLoginInfo(LoginInfo loginInfo) {
            this.loginInfo = loginInfo;
        }
        public EmployeeService getEmployeeService() {
            return employeeService;
        }
        @Resource(name = "employeeService")
        public void setEmployeeService(EmployeeService employeeService) {
            this.employeeService = employeeService;
        }
        
        /**
         * 验证用户是否存在
         */
        @Override
        public String execute() throws Exception {
            Employee employee = new Employee();
            employee.setE_name(loginInfo.getUsername());
            employee.setE_pwd(loginInfo.getPassword());
            boolean result = employeeService.isExists(employee);
            application.put("uname", loginInfo.getUsername());
            System.err.println(result + loginInfo.getUsername());
            if(result)
                return SUCCESS;
            return ERROR;
        }
    
        @Override
        public LoginInfo getModel() {
            return loginInfo;
        }
    
    }
    LoginAction.java

    界面显示如下:

    13.其他功能:增删改查,分页查询,判断该用户是否存在,EmployeeAction.java

    package com.cqvie.action;
    
    import java.io.ByteArrayInputStream;
    import java.io.InputStream;
    import java.io.UnsupportedEncodingException;
    import java.util.Date;
    import java.util.List;
    import java.util.Map;
    
    import javax.annotation.Resource;
    import javax.servlet.http.HttpServletRequest;
    
    import org.apache.struts2.ServletActionContext;
    import org.apache.struts2.interceptor.RequestAware;
    import org.springframework.context.annotation.Scope;
    import org.springframework.stereotype.Component;
    
    import com.cqvie.model.Department;
    import com.cqvie.model.Employee;
    import com.cqvie.service.DepartmentService;
    import com.cqvie.service.EmployeeService;
    import com.cqvie.util.PageBean;
    import com.opensymphony.xwork2.ActionContext;
    import com.opensymphony.xwork2.ActionSupport;
    import com.opensymphony.xwork2.ModelDriven;
    import com.opensymphony.xwork2.Preparable;
    
    @Component("employeeAction")
    @Scope("prototype")
    public class EmployeeAction extends ActionSupport implements ModelDriven<Employee>, RequestAware, Preparable {
    
        private static final long serialVersionUID = 1L;
        
        private int page;
        private PageBean pageBean;
        public int getPage() {
            return page;
        }
        public void setPage(int page) {
            this.page = page;
        }
        public PageBean getPageBean() {
            return pageBean;
        }
        public void setPageBean(PageBean pageBean) {
            this.pageBean = pageBean;
        }
    
        private Map<String, Object> request;
        private Employee emp = new Employee();
        private EmployeeService employeeService;
        private DepartmentService departmentService;
        private InputStream inputStream;
        
        public Employee getEmp() {
            return emp;
        }
        public void setEmp(Employee emp) {
            this.emp = emp;
        }
        public EmployeeService getEmployeeService() {
            return employeeService;
        }
        @Resource
        public void setEmployeeService(EmployeeService employeeService) {
            this.employeeService = employeeService;
        }
        public DepartmentService getDepartmentService() {
            return departmentService;
        }
        @Resource
        public void setDepartmentService(DepartmentService departmentService) {
            this.departmentService = departmentService;
        }
        public Map<String, Object> getRequest() {
            return request;
        }
        public void setRequest(Map<String, Object> request) {
            this.request = request;
        }
        public InputStream getInputStream() {
            return inputStream;
        }
        public void setInputStream(InputStream inputStream) {
            this.inputStream = inputStream;
        }
    
        @Override
        public Employee getModel() {
            return emp;
        }
        
        /**
         * 修改用户时获得该 UUID
         */
        ActionContext context = ActionContext.getContext();
        HttpServletRequest req = (HttpServletRequest) context.get(ServletActionContext.HTTP_REQUEST);
        String e_uuid = req.getParameter("e_uuid");
        
        /**
         * 获得所有员工的信息
         * @return
         */
        public String list() {
            List<Employee> employees = employeeService.getAllEmployee();
            request.put("employees", employees);
            return "list";
        }
        
        /**
         * 跳转到修改、增加界面
         */
        public String input() {
            List<Department> departments = departmentService.getAllDepartment();
            request.put("departments", departments);
            return "input";
        }
        /**
         * 修改界面的显示当前信息
         */
        public void prepareInput() {
            System.err.println("*******" + e_uuid + "********");
            if(e_uuid != null) {
                emp = employeeService.getEmployee(e_uuid);
            }
        }
        
        /**
         * 更新或者保存信息
         * @return
         */
        public String save() {
            if(e_uuid == null) {
                emp.setE_createDate(new Date());
            }
            employeeService.saveOrUpdateEmployee(emp);
            return "success";
        }
        public void prepareSave() {
            System.out.println("****************save****************");
            if(e_uuid == null) {
                emp = new Employee();
            } else {
                emp = employeeService.getEmployee(e_uuid);
            }
        }
        
        /**
         * 员工的删除
         * @return
         */
        /*public String delete() {
            employeeService.deleteEmployee(emp);
            return "delete";
        }*/
        
        /**
         * 员工的 Ajax 删除
         * @return
         */
        public String delete() {
            try {
                employeeService.deleteEmployee(emp);
                inputStream = new ByteArrayInputStream("1".getBytes("UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                try {
                    inputStream = new ByteArrayInputStream("0".getBytes("UTF-8"));
                } catch (UnsupportedEncodingException e1) {
                    e1.printStackTrace();
                }
            }
            return "ajax-success";
        }
        
        /**
         * 用户的修改
         * @return
         */
        public String update() {
            List<Department> departments = departmentService.getAllDepartment();
            request.put("departments", departments);
            return "update";
        }
        
        /**
         * 检验用户名是否存在
         * @return
         * @throws UnsupportedEncodingException
         */
        public String validateE_name() throws UnsupportedEncodingException {
            System.err.println(employeeService.getEmployeeByName(emp.getE_name()));
            if(employeeService.getEmployeeByName(emp.getE_name())) {
                inputStream = new ByteArrayInputStream("0".getBytes("UTF-8"));
            } else {
                inputStream = new ByteArrayInputStream("1".getBytes("UTF-8"));
            }
            return "ajax-success";
        }
        
        @Override
        public void prepare() throws Exception {}
        
        /**
         * 分页显示数据
         * @return
         */
        public String page() {
            //分页的pageBean,参数pageSize表示每页显示记录数,page为当前页   
            this.pageBean = employeeService.queryForPage(5, page);
            List<Employee> pag = pageBean.getList();
            request.put("employees", pag);
            return "page";
        }
        
    }
    EmployeeAction.java

    14.没有分页的显示界面 index.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>首页</title>
            <style type="text/css">
                a { color: blue; }
            </style>
            <script type="text/javascript" src="js/jquery.js"></script>
            <script type="text/javascript">
                $(function() {
                    //提示框
                    $(".delete").click(function() {
                        var name = $(this).next(":input").val();
                        var flag = confirm("确定要删除  " + name + " 的信息吗?");
                        if(flag) {
                            var $tr = $(this).parent().parent();
                            var url = this.href;// "emp-delete";
                            var args = {};
                            $.post(url, args, function(data) {
                                if(data == "1") {
                                    alert("删除成功!");
                                    $tr.remove();
                                } else {
                                    alert("删除失败!");
                                }
                            });
                        }
                        //取消删除
                        return false;
                    });
                });
            </script>
        </head>
    <body>
        <h1>Welcome,<s:property value="#application.uname" /></h1>    <hr>
        
        <a href="emp-input">增加用户</a>    <br><br>
        <s:if test="#request.employees == null || #request.employees.size() == 0">没有任何员工的信息!</s:if>
        <s:else>
            <table border="1" cellpadding="5" cellspacing="0">
                <tr>
                    <td>UUID</td>
                    <td>姓名</td>
                    <td>密码</td>
                    <td>出生日期</td>
                    <td>邮箱</td>
                    <td>部门名称</td>
                    <td>创建时间</td>
                    <td>操作</td>
                </tr>
                <s:iterator value="#request.employees" var="e">
                    <tr>
                        <td>${e.e_uuid}</td>
                        <td>${e.e_name}</td>
                        <td>${e.e_pwd}</td>
                        <td>${e.e_birthday}</td>
                        <td>${e.e_email}</td>
                        <td>${e.e_department.d_name}</td>
                        <td>${e.e_createDate}</td>
                        <td>
                            <a href="emp-input?e_uuid=${e.e_uuid }">修改</a>    &nbsp;&nbsp;&nbsp;
                            <a href="emp-delete?e_uuid=${e.e_uuid }" class="delete">删除</a>
                            <input type="hidden" value="${e.e_name}" />
                        </td>
                    </tr>
                </s:iterator>
            </table>
        </s:else>
        
        <s:debug></s:debug>
    </body>
    </html>
    index.jsp

    有分页的显示页面 index_page.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>首页2</title>
            <style type="text/css">
                a { color: blue; }
            </style>
            <script type="text/javascript" src="js/jquery.js"></script>
            <script type="text/javascript">
                $(function() {
                    //提示框
                    $(".delete").click(function() {
                        var name = $(this).next(":input").val();
                        var flag = confirm("确定要删除  " + name + " 的信息吗?");
                        if(flag) {
                            var $tr = $(this).parent().parent();
                            var url = this.href;// "emp-delete";
                            var args = {};
                            $.post(url, args, function(data) {
                                if(data == "1") {
                                    alert("删除成功!");
                                    $tr.remove();
                                } else {
                                    alert("删除失败!");
                                }
                            });
                        }
                        //取消删除
                        return false;
                    });
                });
            </script>
        </head>
    <body>
        <h1>Welcome,<s:property value="#application.uname" /></h1>    <hr>
        
        <a href="emp-input">增加用户</a>    <br><br>
        <s:if test="#request.employees == null || #request.employees.size() == 0">没有任何员工的信息!</s:if>
        <s:else>
            <table border="1" cellpadding="5" cellspacing="0">
                <tr>
                    <td>UUID</td>
                    <td>姓名</td>
                    <td>密码</td>
                    <td>出生日期</td>
                    <td>邮箱</td>
                    <td>部门名称</td>
                    <td>创建时间</td>
                    <td>操作</td>
                </tr>
                <s:iterator value="#request.employees" var="pag">
                    <tr>
                        <td>${pag.e_uuid}</td>
                        <td>${pag.e_name}</td>
                        <td>${pag.e_pwd}</td>
                        <td>${pag.e_birthday}</td>
                        <td>${pag.e_email}</td>
                        <td>${pag.e_department.d_name}</td>
                        <td>${pag.e_createDate}</td>
                        <td>
                            <a href="emp-input?e_uuid=${pag.e_uuid }">修改</a>    &nbsp;&nbsp;&nbsp;
                            <a href="emp-delete?e_uuid=${pag.e_uuid }" class="delete">删除</a>
                            <input type="hidden" value="${pag.e_name}" />
                        </td>
                    </tr>
                </s:iterator>
            </table>
        </s:else>
        
        共 <s:property value="pageBean.allRow"/> 条记录   
        共 <s:property value="pageBean.totalPage"/> 页   
        当前第 <s:property value="pageBean.currentPage"/><br/>   
        <s:if test="%{pageBean.currentPage == 1}">   
          第一页 上一页   
        </s:if>   
        <s:else>   
          <a href="emp-page?page=1">首页</a>   
          <a href="emp-page?page=<s:property value="%{pageBean.currentPage-1}"/>">上一页</a>   
        </s:else>   
        <s:if test="%{pageBean.currentPage != pageBean.totalPage}">   
          <a href="emp-page?page=<s:property value="%{pageBean.currentPage+1}"/>">下一页</a>   
          <a href="emp-page?page=<s:property value="pageBean.totalPage"/>">最后一页</a>   
        </s:if>   
        <s:else>   
          下一页 最后一页   
        </s:else>  
    <s:debug></s:debug>
    </body>
    </html>
    index_page.jsp

    界面显示如下(上图带分页):

    15.增加信息和修改信息的界面,包含检验用户是否已存在的 Ajax 验证:

    <%@ 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>增加用户</title>
            <script type="text/javascript" src="js/jquery.js"></script>
            <script type="text/javascript">
                $(function() {
                    //检验用户名是否存在
                    $(":input[name=e_name]").change(function() {
                        var val = $(this).val();
                        val = $.trim(val);
                        var $this = $(this);
                        
                        if(val != "") {
                            $this.nextAll("font").remove();
                            
                            var url = "emp-validateE_name";
                            var args = {"e_name":val};
                            $.post(url, args, function(data) {
                                if(data == "1") {    //表示可用
                                    $this.after("<font color='green'>该姓名可以使用!</font>");
                                } else if(data == "0") {    //表示不可用
                                    $this.after("<font color='red'>该姓名已存在!</font>");
                                } else {    //表示服务器错误
                                    alert("服务器错误!");
                                }
                            });
                        } else {
                            alert("姓名不能为空!");
                            this.focus();
                        }
                    });
                });
            </script>
        </head>
    <body>
        <h1>添加用户</h1>    <hr>
        
        <s:form action="emp-save" method="post">
            <s:if test="e_uuid != null">
                <s:textfield name="e_name" label="姓名" disabled="true" />
                <s:hidden name="e_uuid" />
            </s:if>
            <s:else>
                <s:textfield name="e_name" label="姓名" />
            </s:else>
            <s:textfield name="e_pwd" label="密码" />
            <s:textfield name="e_email" label="邮箱" />
            
            <s:textfield name="e_birthday" label="出生日期">
              <s:param name="value"><s:date name="e_birthday" format="yyyy-MM-dd"/></s:param>
            </s:textfield>
            
            <s:select list="#request.departments" listKey="d_uuid" listValue="d_name" name="e_department.d_uuid" label="部门" />
            <s:submit value="添加" />
        </s:form>
        
        <s:debug></s:debug>
    </body>
    </html>
    emp-add.jsp

    显示页面如下(右图为修改界面):

    16.至此我们的 SSH 程序已经写完了,欢迎大家转载收藏,欢迎诸多大牛在评论区指教,博主非常感谢您的观看!!!

  • 相关阅读:
    Python基础 索引页
    【Python基础】循环输出随机数例子:生存游戏
    杂项索引页
    【Python 基础】对象持久化的小例子
    《期权的智慧》笔记
    《博弈论》笔记
    别人都在马斯洛金字塔的下部,而你在顶层?
    提高生命的效率
    《不讲逻辑的世界里的逻辑艺术》(The Art of Logic in an Illogical World)笔记
    美德的”近敌“
  • 原文地址:https://www.cnblogs.com/yjq520/p/6705959.html
Copyright © 2020-2023  润新知