• Java进阶知识29 Struts2+Spring+Hibernate+Oracle 注解版整合实例


     本文知识点(目录):

        1、本文整合实例最终效果图展示
        2、导读
            2.1、开发技术概述
            2.2、本项目使用的jar包、项目结构图
        3、本文所有代码(SSH注解版)
            3.1、Oracle 数据库建表脚本
            3.2、web.xml 配置文件
            3.3、User、Role、Department 实体类
            3.4、dao层
            3.5、service层
            3.6、action层
            3.7、Struts2配置文件
            3.8、Spring配置文件
            3.9、前端页面



    1、本文整合实例最终效果图展示  

    2、导读                

    2.1、开发技术概述

        a.本文使用的是Struts2+Spring+Hibernate框架,Oracle 11g,tomcat-7.0.96,JDK-1.8,MyEclipse10.6,采用了“注解版”的方式开发的;

        b.本文所有Hibernate配置文件、dao层、service层、action层 等等,统统交给Spring容器来管理;

        c.本文只实现了用户登录(含账号查询)、新增用户、查询所有用户信息、根据id查询;

        d.通过反射获取子类的泛型实体对象;

        e.本项目所采用的编码格式都是 UTF-8;

        f.本项目的Struts2和Spring的配置文件都是放在src目录下。

    2.2、本项目使用的jar包、项目结构图

          

    3、本文所有代码(SSH注解版)  

    3.1、Oracle 数据库建表脚本

     1 /*==============================================================*/
     2 /* DBMS name:      ORACLE Version 11g                           */
     3 /* Created on:     2020/2/6 10:44:31                           */
     4 /*==============================================================*/
     5 
     6 
     7 alter table role
     8    drop constraint FK_ROLE_USERS_ROL_USERS;
     9 
    10 alter table users
    11    drop constraint FK_USERS_USERS_DEP_DEPARTME;
    12 
    13 drop table department cascade constraints;
    14 
    15 drop index users_role_fk_FK;
    16 
    17 drop table role cascade constraints;
    18 
    19 drop index users_department_fk_FK;
    20 
    21 drop table users cascade constraints;
    22 
    23 /*==============================================================*/
    24 /* Table: "department"                                          */
    25 /*==============================================================*/
    26 create table department
    27 (
    28    id                 INTEGER              not null,
    29    deptname           VARCHAR2(20),
    30    description        VARCHAR2(40),
    31    constraint PK_DEPARTMENT primary key (id)
    32 );
    33 
    34 /*==============================================================*/
    35 /* Table: "role"                                                */
    36 /*==============================================================*/
    37 create table role 
    38 (
    39    id                 INTEGER              not null,
    40    user_id            INTEGER,
    41    rolename           VARCHAR2(20),
    42    constraint PK_ROLE primary key (id)
    43 );
    44 
    45 /*==============================================================*/
    46 /* Index: "users_role_fk_FK"                                    */
    47 /*==============================================================*/
    48 create index users_role_fk_FK on role (
    49    user_id ASC
    50 );
    51 
    52 /*==============================================================*/
    53 /* Table: "users"                                               */
    54 /*==============================================================*/
    55 create table users 
    56 (
    57    id                 INTEGER              not null,
    58    dept_id            INTEGER,
    59    name               VARCHAR2(20),
    60    account            VARCHAR2(20),
    61    password           VARCHAR2(50),
    62    email              VARCHAR2(30),
    63    telphone           VARCHAR2(20),
    64    flag               SMALLINT, -- Boolean 类型
    65    constraint PK_USERS primary key (id)
    66 );
    67 
    68 /*==============================================================*/
    69 /* Index: "users_department_fk_FK"                              */
    70 /*==============================================================*/
    71 create index users_department_fk_FK on users (
    72    dept_id ASC
    73 );
    74 
    75 alter table role
    76    add constraint FK_ROLE_USERS_ROL_USERS foreign key (user_id)
    77       references users (id);
    78 
    79 alter table users
    80    add constraint FK_USERS_USERS_DEP_DEPARTME foreign key (dept_id)
    81       references department (id);

    3.2、web.xml 配置文件(程序总入口)

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <web-app version="3.0" 
     3     xmlns="http://java.sun.com/xml/ns/javaee" 
     4     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     5     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
     6     http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
     7   <display-name></display-name>    
     8   <welcome-file-list>
     9     <welcome-file>index.jsp</welcome-file>
    10   </welcome-file-list>
    11   
    12       <!-- spring监听器 begin-->
    13       <context-param>
    14         <param-name>contextConfigLocation</param-name>
    15         <param-value>/WEB-INF/classes/spring/beans_*.xml</param-value>
    16     </context-param>
    17 
    18     <listener>
    19         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    20     </listener>
    21     <!-- spring监听器 end-->
    22     
    23     <!-- struts2过滤器 begin -->
    24     <filter>
    25         <filter-name>struts2</filter-name>
    26         <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    27     </filter>
    28 
    29     <filter-mapping>
    30         <filter-name>struts2</filter-name>
    31         <url-pattern>/*</url-pattern>
    32     </filter-mapping>
    33     <!-- struts2过滤器 end -->
    34 </web-app>

    3.3、User、Role、Department 实体类

    User.java

      1 package com.oa.shore.entity;
      2 
      3 import java.util.HashSet;
      4 import java.util.Set;
      5 
      6 import javax.persistence.Entity;
      7 import javax.persistence.GeneratedValue;
      8 import javax.persistence.GenerationType;
      9 import javax.persistence.Id;
     10 import javax.persistence.JoinColumn;
     11 import javax.persistence.ManyToOne;
     12 import javax.persistence.OneToMany;
     13 import javax.persistence.SequenceGenerator;
     14 import javax.persistence.Table;
     15 
     16 import org.hibernate.annotations.Cascade;
     17 import org.hibernate.annotations.CascadeType;
     18 
     19 /**
     20  * @author DSHORE/2020-2-6
     21  * 
     22  */
     23 @Entity
     24 @Table(name="users")
     25 public class User {
     26     private Integer id;
     27     private String name;
     28     private String account;
     29     private String password;
     30     private String email;
     31     private String telphone;
     32     private Boolean flag;
     33     private Department dept;
     34     private Set<Role> roles = new HashSet<Role>();
     35 
     36     @Id
     37     @SequenceGenerator(name = "userid_seq",sequenceName="users_seq")
     38     @GeneratedValue(strategy=GenerationType.SEQUENCE,generator="userid_seq")
     39     public Integer getId() {
     40         return id;
     41     }
     42 
     43     public void setId(Integer id) {
     44         this.id = id;
     45     }
     46 
     47     public String getName() {
     48         return name;
     49     }
     50 
     51     public void setName(String name) {
     52         this.name = name;
     53     }
     54 
     55     public String getAccount() {
     56         return account;
     57     }
     58 
     59     public void setAccount(String account) {
     60         this.account = account;
     61     }
     62 
     63     public String getPassword() {
     64         return password;
     65     }
     66 
     67     public void setPassword(String password) {
     68         this.password = password;
     69     }
     70 
     71     public String getEmail() {
     72         return email;
     73     }
     74 
     75     public void setEmail(String email) {
     76         this.email = email;
     77     }
     78 
     79     public String getTelphone() {
     80         return telphone;
     81     }
     82 
     83     public void setTelphone(String telphone) {
     84         this.telphone = telphone;
     85     }
     86 
     87     public Boolean getFlag() {
     88         return flag;
     89     }
     90 
     91     public void setFlag(Boolean flag) {
     92         this.flag = flag;
     93     }
     94 
     95     @ManyToOne
     96     @JoinColumn(name="dept_id")
     97     @Cascade(CascadeType.ALL)
     98     public Department getDept() {
     99         return dept;
    100     }
    101 
    102     public void setDept(Department dept) {
    103         this.dept = dept;
    104     }
    105 
    106     @OneToMany
    107     @JoinColumn(name="user_id")
    108     @Cascade(CascadeType.ALL)
    109     public Set<Role> getRoles() {
    110         return roles;
    111     }
    112 
    113     public void setRoles(Set<Role> roles) {
    114         this.roles = roles;
    115     }
    116 }

    Role.java

     1 package com.oa.shore.entity;
     2 
     3 import javax.persistence.Entity;
     4 import javax.persistence.GeneratedValue;
     5 import javax.persistence.GenerationType;
     6 import javax.persistence.Id;
     7 import javax.persistence.SequenceGenerator;
     8 
     9 /**
    10  * @author DSHORE/2020-2-6
    11  *
    12  */
    13 @Entity
    14 public class Role {
    15     private Integer id;
    16     private String roleName;
    17     
    18     @Id
    19     @SequenceGenerator(name="roleid_seq",sequenceName="role_seq")
    20     @GeneratedValue(strategy=GenerationType.SEQUENCE,generator="roleid_seq")
    21     public Integer getId() {
    22         return id;
    23     }
    24 
    25     public void setId(Integer id) {
    26         this.id = id;
    27     }
    28 
    29     public String getRoleName() {
    30         return roleName;
    31     }
    32 
    33     public void setRoleName(String roleName) {
    34         this.roleName = roleName;
    35     }
    36 }

    Department.java

     1 package com.oa.shore.entity;
     2 
     3 import javax.persistence.Entity;
     4 import javax.persistence.GeneratedValue;
     5 import javax.persistence.GenerationType;
     6 import javax.persistence.Id;
     7 import javax.persistence.SequenceGenerator;
     8 
     9 /**
    10  * @author DSHORE/2020-2-6
    11  *
    12  */
    13 @Entity
    14 public class Department {
    15     private Integer id;
    16     private String deptName;
    17     private String description;
    18 
    19     @Id
    20     @SequenceGenerator(name="deptid_seq",sequenceName="dept_seq")
    21     @GeneratedValue(strategy=GenerationType.SEQUENCE,generator="deptid_seq")
    22     public Integer getId() {
    23         return id;
    24     }
    25 
    26     public void setId(Integer id) {
    27         this.id = id;
    28     }
    29 
    30     public String getDeptName() {
    31         return deptName;
    32     }
    33 
    34     public void setDeptName(String deptName) {
    35         this.deptName = deptName;
    36     }
    37 
    38     public String getDescription() {
    39         return description;
    40     }
    41 
    42     public void setDescription(String description) {
    43         this.description = description;
    44     }
    45 }

    3.4、dao层

      3.4.1、各个dao的公共部分:接口IBaseDao和实现类BaseDao

     1 package com.oa.common.dao;
     2 
     3 import java.util.List;
     4 
     5 /**
     6  * @author DSHORE/2020-2-6
     7  *
     8  */
     9 public interface IBaseDao<T> {
    10     public int add(T entity);//新增
    11 
    12     public List<T> listAll();//查询所有
    13     
    14     public T findById(Integer id);//根据id查询
    15 }
    16 
    17 
    18 /**
    19  * 下面是IBaseDao接口的实现类BaseDao
    20  *
    21  */
    22 
    23 
    24 package com.oa.common.dao.impl;
    25 
    26 import java.lang.reflect.ParameterizedType;
    27 import java.lang.reflect.Type;
    28 import java.util.List;
    29 
    30 import org.hibernate.Query;
    31 import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
    32 import org.springframework.stereotype.Repository;
    33 
    34 import com.oa.common.dao.IBaseDao;
    35 
    36 /**
    37  * @author DSHORE/2020-2-6
    38  *
    39  */
    40 @Repository("baseDao")
    41 public class BaseDao<T> extends HibernateDaoSupport implements IBaseDao<T>  {
    42     /*//此处叫给spring自动管理/注入了(extends HibernateDaoSupport)
    43     @Autowired
    44     private SessionFactory sessionFactory;
    45      
    46     public void setSessionFactory(SessionFactory sessionFactory) {
    47         this.sessionFactory = sessionFactory;
    48     }*/
    49     
    50     private Class<T> clazz;
    51 
    52     //反射机制,获取对应的对象
    53     @SuppressWarnings("unchecked")
    54     public BaseDao() {//构造函数的作用:获取对应的实体类对象
    55         // this——表示当前类(UserDao)
    56         // this.getClass()——当前运行类的字节码(UserDao.class)
    57         // this.getClass().getGenericSuperclass()——当前运行类的父类(BaseDao<T>,以为User为例,那就是BaseDao<User>)
    58         Type type = this.getClass().getGenericSuperclass(); // generic 泛型
    59         if(type instanceof ParameterizedType){
    60             // 强制转化“参数化类型”
    61             ParameterizedType parameterizedType = (ParameterizedType) type;
    62             // 参数化类型中可能有多个泛型参数
    63             Type[] types = parameterizedType.getActualTypeArguments();
    64             // 获取数据的第一个元素(User.class)
    65             clazz = (Class<T>) types[0]; // com.oa.shore.entity.User.class 
    66         }
    67     }
    68     
    69     @Override //新增
    70     public int add(T entity) {
    71         return (Integer) getHibernateTemplate().save(entity);
    72         //return (Integer) sessionFactory.getCurrentSession().save(entity);
    73     }
    74 
    75     @SuppressWarnings("unchecked")
    76     @Override //查询所有
    77     public List<T> listAll() {
    78         //Query query = sessionFactory.getCurrentSession().createQuery("from " + clazz.getSimpleName());
    79         Query query = getSession().createQuery("from " + clazz.getSimpleName() + " order by id asc");
    80         return query.list();
    81     }
    82 
    83     @Override  //根据id查询
    84     public T findById(Integer id) {
    85         return (T) getHibernateTemplate().get(clazz, id);
    86     }
    87 }

      3.4.2、dao层其他接口和实现类

    User实体类的dao层:接口和实现类

     1 package com.oa.shore.dao;
     2 
     3 import com.oa.common.dao.IBaseDao;
     4 import com.oa.shore.entity.User;
     5 
     6 /**
     7  * @author DSHORE/2020-2-6
     8  *
     9  */
    10 public interface IUserDao extends IBaseDao<User> {
    11 
    12     public User findByAccount(String account);//根据账号查询
    13 }
    14 
    15 
    16 /**
    17  * 下面是IUserDao接口的实现类UserDao 
    18  *
    19  */
    20 
    21 
    22 package com.oa.shore.dao.impl;
    23 
    24 import java.util.List;
    25 
    26 import org.hibernate.Query;
    27 import org.springframework.stereotype.Repository;
    28 
    29 import com.oa.common.dao.impl.BaseDao;
    30 import com.oa.shore.dao.IUserDao;
    31 import com.oa.shore.entity.User;
    32 
    33 /**
    34  * @author DSHORE/2020-2-6
    35  *
    36  */
    37 @Repository("userDao")
    38 public class UserDao extends BaseDao<User> implements IUserDao {
    39 
    40     @Override //根据账号查询
    41     public User findByAccount(String account) {
    42         Query query = getSession().createQuery("from User where account=:account"); //:account是命名参数
    43         query.setParameter("account", account);
    44         @SuppressWarnings("unchecked")
    45         List<User> users = query.list();
    46         if (users != null && users.size() > 0) {
    47             return users.get(0);
    48         }
    49         return null;
    50     }
    51 }

    Role实体类的dao层:接口和实现类

     1 package com.oa.shore.dao;
     2 
     3 import com.oa.common.dao.IBaseDao;
     4 import com.oa.shore.entity.Role;
     5 
     6 /**
     7  * @author DSHORE/2020-2-20
     8  *
     9  */
    10 public interface IRoleDao extends IBaseDao<Role> {
    11 
    12 }
    13 
    14 
    15 /**
    16  * 下面是IRoleDao接口的实现类RoleDao 
    17  *
    18  */
    19 
    20 
    21 package com.oa.shore.dao.impl;
    22 
    23 import org.springframework.stereotype.Repository;
    24 
    25 import com.oa.common.dao.impl.BaseDao;
    26 import com.oa.shore.dao.IRoleDao;
    27 import com.oa.shore.entity.Role;
    28 
    29 /**
    30  * @author DSHORE/2020-2-20
    31  *
    32  */
    33 @Repository("roleDao")
    34 public class RoleDao extends BaseDao<Role> implements IRoleDao {
    35 
    36 }

    Department实体类的dao层:接口和实现类

     1 package com.oa.shore.dao;
     2 
     3 import com.oa.common.dao.IBaseDao;
     4 import com.oa.shore.entity.Department;
     5 
     6 /**
     7  * @author DSHORE/2020-2-19
     8  *
     9  */
    10 public interface IDepartmentDao extends IBaseDao<Department> {
    11 
    12 }
    13 
    14 
    15 /**
    16  * 下面是IDepartmentDao接口的实现类DepartmentDao 
    17  *
    18  */
    19 
    20 
    21 package com.oa.shore.dao.impl;
    22 
    23 import org.springframework.stereotype.Repository;
    24 
    25 import com.oa.common.dao.impl.BaseDao;
    26 import com.oa.shore.dao.IDepartmentDao;
    27 import com.oa.shore.entity.Department;
    28 
    29 /**
    30  * @author DSHORE/2020-2-19
    31  *
    32  */
    33 @Repository("departmentDao")
    34 public class DepartmentDao extends BaseDao<Department> implements IDepartmentDao {
    35 
    36 }

    3.5、service层

    User实体类的service层: 接口和实现类

     1 package com.oa.shore.service;
     2 
     3 import java.util.List;
     4 
     5 import com.oa.shore.entity.User;
     6 
     7 /**
     8  * @author DSHORE/2020-2-6
     9  *
    10  */
    11 public interface IUserService {
    12     public int save(User user);//新增
    13 
    14     public List<User> listAll();//查询所有
    15     
    16     public User findByAccount(String account);//根据账号查询
    17 }
    18 
    19 
    20 /**
    21  * 下面是IUserService接口的实现类UserService 
    22  *
    23  */
    24 
    25 
    26 package com.oa.shore.service.impl;
    27 
    28 import java.util.List;
    29 
    30 import org.springframework.beans.factory.annotation.Autowired;
    31 import org.springframework.stereotype.Service;
    32 
    33 import com.oa.shore.dao.IUserDao;
    34 import com.oa.shore.entity.User;
    35 import com.oa.shore.service.IUserService;
    36 
    37 /**
    38  * @author DSHORE/2020-2-6
    39  *
    40  */
    41 @Service("userService")
    42 public class UserService implements IUserService {
    43     
    44     @Autowired
    45     private IUserDao userDao; //注入
    46     public void setUserDao(IUserDao userDao) {
    47         this.userDao = userDao;
    48     }
    49 
    50     @Override //新增
    51     public int save(User user) {
    52         return userDao.add(user);
    53     }
    54 
    55     @Override //查询所有
    56     public List<User> listAll() {
    57         return userDao.listAll();
    58     }
    59 
    60     @Override //根据账号查询
    61     public User findByAccount(String account) {
    62         return userDao.findByAccount(account);
    63     }
    64 }

    Role实体类的service层: 接口和实现类

     1 package com.oa.shore.service;
     2 
     3 import java.util.List;
     4 
     5 import com.oa.shore.entity.Role;
     6 
     7 /**
     8  * @author DSHORE/2020-2-19
     9  *
    10  */
    11 public interface IRoleService {
    12 
    13     public List<Role> listAll();//查询所有角色
    14 
    15 }
    16 
    17 
    18 /**
    19  * 下面是RoleService 接口的实现类RoleService 
    20  *
    21  */
    22 
    23 
    24 package com.oa.shore.service.impl;
    25 
    26 import java.util.List;
    27 
    28 import org.springframework.beans.factory.annotation.Autowired;
    29 import org.springframework.stereotype.Service;
    30 
    31 import com.oa.shore.dao.IRoleDao;
    32 import com.oa.shore.entity.Role;
    33 import com.oa.shore.service.IRoleService;
    34 
    35 /**
    36  * @author DSHORE/2020-2-19
    37  *
    38  */
    39 @Service("roleService")
    40 public class RoleService implements IRoleService {
    41 
    42     @Autowired
    43     private IRoleDao roleDao;//注入
    44     public void setRoleDao(IRoleDao roleDao) {
    45         this.roleDao = roleDao;
    46     }
    47     
    48     @Override
    49     public List<Role> listAll() {
    50         return roleDao.listAll();
    51     }
    52 
    53 }

    Department实体类的service层: 接口和实现类

     1 package com.oa.shore.service;
     2 
     3 import java.util.List;
     4 
     5 import com.oa.shore.entity.Department;
     6 
     7 /**
     8  * @author DSHORE/2020-2-19
     9  *
    10  */
    11 public interface IDepartmentService {
    12 
    13     public List<Department> listAll();//查询所有部门
    14 
    15     public Department findById(Integer departmentId);//根据id查询
    16 
    17 }
    18 
    19 
    20 /**
    21  * 下面是IDepartmentService接口的实现类DepartmentService 
    22  *
    23  */
    24 
    25 
    26 package com.oa.shore.service.impl;
    27 
    28 import java.util.List;
    29 
    30 import org.springframework.beans.factory.annotation.Autowired;
    31 import org.springframework.stereotype.Service;
    32 
    33 import com.oa.shore.dao.IDepartmentDao;
    34 import com.oa.shore.entity.Department;
    35 import com.oa.shore.service.IDepartmentService;
    36 
    37 /**
    38  * @author DSHORE/2020-2-19
    39  *
    40  */
    41 @Service("departmentService")
    42 public class DepartmentService implements IDepartmentService {
    43 
    44     @Autowired
    45     private IDepartmentDao departmentDao;
    46     public void setDepartmentDao(IDepartmentDao departmentDao) {
    47         this.departmentDao = departmentDao;
    48     }
    49     
    50     @Override
    51     public List<Department> listAll() {
    52         return departmentDao.listAll();
    53     }
    54 
    55     @Override
    56     public Department findById(Integer departmentId) {
    57         return departmentDao.findById(departmentId);
    58     }
    59 
    60 }

    3.6、action层(控制层:controller)

    UserAction.java

      1 package com.oa.shore.action;
      2 
      3 import java.util.ArrayList;
      4 import java.util.HashMap;
      5 import java.util.List;
      6 import java.util.Map;
      7 import org.springframework.beans.factory.annotation.Autowired;
      8 import org.springframework.stereotype.Controller;
      9 
     10 import com.oa.shore.entity.Department;
     11 import com.oa.shore.entity.Role;
     12 import com.oa.shore.entity.User;
     13 import com.oa.shore.service.IDepartmentService;
     14 import com.oa.shore.service.IRoleService;
     15 import com.oa.shore.service.IUserService;
     16 import com.opensymphony.xwork2.ActionContext;
     17 import com.opensymphony.xwork2.ActionSupport;
     18 import com.opensymphony.xwork2.ModelDriven;
     19 
     20 /**
     21  * @author DSHORE/2020-2-6
     22  *
     23  */
     24 @Controller("userAction")  //或者 @Controller(value="userAction"),或者不注释也没问题
     25 public class UserAction extends ActionSupport implements ModelDriven<User> {
     26     private static final long serialVersionUID = 2568378173294235393L;
     27     
     28     @Autowired
     29     private IUserService userService;
     30     public void setUserService(IUserService userService) {
     31         this.userService = userService;
     32     }
     33     
     34     @Autowired
     35     private IDepartmentService departmentService;
     36     public void setDepartmentService(IDepartmentService departmentService) {
     37         this.departmentService = departmentService;
     38     }
     39     
     40     @Autowired
     41     private IRoleService roleService;
     42     public void setRoleService(IRoleService roleService) {
     43         this.roleService = roleService;
     44     }
     45     
     46     private User user;
     47     private List<User> userList = new ArrayList<User>();
     48     private Map<Integer, String> departments = new HashMap<Integer, String>();
     49     private Map<Integer, String> roles2 = new HashMap<Integer, String>();
     50     private Integer departmentId;
     51     private String[] roleIds;
     52     
     53     private String errorMessage; //登录时,账号/密码错误,提示信息
     54     
     55     //登录
     56     public String login() {
     57         String account = user.getAccount().trim();
     58         String password = user.getPassword().trim();
     59         //根据用户账号名称查询User对象
     60         User dbUser = userService.findByAccount(account);
     61         if (dbUser == null) {   //用户不存在
     62             errorMessage = "账号不存在,请重新输入!";
     63             return ERROR;
     64         } else {
     65             if (!password.equals(dbUser.getPassword())) {
     66                 errorMessage = "密码错误,请重新输入!";
     67                 return ERROR;
     68             }else {
     69                 //把该用户(数据库中查到的)保存到session中
     70                 ActionContext.getContext().getSession().put("currentUser", dbUser);
     71             }
     72         }
     73         return SUCCESS;
     74     }
     75 
     76     //查询所用户信息
     77     public String listAll() {
     78         userList = userService.listAll();
     79         return "listAll";
     80     }
     81     
     82     //添加用户前,先把部门列表和角色列表查询出来
     83     public String toAdd() {
     84         List<Department> allDepartments = departmentService.listAll();
     85         if (allDepartments != null && allDepartments.size() > 0) {
     86             for (Department d : allDepartments) {
     87                 departments.put(d.getId(), d.getDeptName());
     88             }
     89         }
     90         List<Role> allRoles = roleService.listAll();
     91         if (allRoles != null && allRoles.size() > 0) {
     92             for (Role r : allRoles) {
     93                 roles2.put(r.getId(), r.getRoleName());
     94             }
     95         }
     96         return "toAdd";
     97     }
     98         
     99     //新增用户
    100     public String save() {
    101         if (user != null) {
    102             if (departmentId != null) {
    103                 user.setDept(departmentService.findById(departmentId));
    104             }
    105             userService.save(user);
    106             /*
    107              * 由于数据表设计缺陷,故role表的数据不再做保存处理;
    108              * 建议:User和Role建立一个中间表的形式连接起来,这样既可以减少数据表之间的数据冗余的情况,又可以避免我现在出现情况。
    109              * (不想改了,就这样吧,改底层太麻烦了,要改很多;反正只是演示一下SSH框架下注解版的整合教程)
    110              * */role做保存处理的另一个版本,SSH框架,xml版:https://www.cnblogs.com/dshore123/p/12354195.html
    111         }
    112         return "success";
    113     }
    114         
    115     
    116     @Override
    117     public User getModel() {
    118         return user;
    119     }
    120 
    121     public User getUser() {
    122         return user;
    123     }
    124 
    125     public void setUser(User user) {
    126         this.user = user;
    127     }
    128 
    129     public List<User> getUserList() {
    130         return userList;
    131     }
    132 
    133     public void setUserList(List<User> userList) {
    134         this.userList = userList;
    135     }
    136 
    137     public String getErrorMessage() {
    138         return errorMessage;
    139     }
    140 
    141     public void setErrorMessage(String errorMessage) {
    142         this.errorMessage = errorMessage;
    143     }
    144 
    145     public Map<Integer, String> getDepartments() {
    146         return departments;
    147     }
    148 
    149     public void setDepartments(Map<Integer, String> departments) {
    150         this.departments = departments;
    151     }
    152 
    153     public Map<Integer, String> getRoles2() {
    154         return roles2;
    155     }
    156 
    157     public void setRoles2(Map<Integer, String> roles2) {
    158         this.roles2 = roles2;
    159     }
    160 
    161     public Integer getDepartmentId() {
    162         return departmentId;
    163     }
    164 
    165     public void setDepartmentId(Integer departmentId) {
    166         this.departmentId = departmentId;
    167     }
    168 
    169     public String[] getRoleIds() {
    170         return roleIds;
    171     }
    172 
    173     public void setRoleIds(String[] roleIds) {
    174         this.roleIds = roleIds;
    175     }
    176 }

    3.7、Struts2配置文件

    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     <!-- 动态方法调用,为true时,就可以在struts.xml配置“*”的通配符 -->
     8     <constant name="struts.enable.DynamicMethodInvocation" value="true" />
     9     <!-- devMode被激活的模式下,能够明显的提高开发效率,它会提供更多的日志或着debug信息,但在性能方面会付出一定的代价 -->
    10     <constant name="struts.devMode" value="true" />  <!-- 默认为false -->
    11     <constant name="struts.ui.theme" value="simple" /><!-- 作用:使,有s标签的页面显示同一行 -->
    12 
    13     <package name="user" namespace="/" extends="struts-default">
    14         <action name="userAction" class="com.oa.shore.action.UserAction">
    15             <result name="success" type="redirectAction">userAction!listAll</result>
    16             <result name="error" type="redirect">/jsp/user/login.jsp</result>
    17             <result name="listAll">/jsp/user/user-list.jsp</result>
    18             <result name="toAdd">/jsp/user/user-add.jsp</result>
    19         </action>
    20     </package>
    21 </struts>

    3.8、Spring配置文件

    beans_common.xml (hibernate的配置文件,包括连接池等,全交给Spring容器来管理)

     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     xmlns:aop="http://www.springframework.org/schema/aop"
     5     xmlns:tx="http://www.springframework.org/schema/tx"
     6     xsi:schemaLocation="
     7        http://www.springframework.org/schema/beans
     8        http://www.springframework.org/schema/beans/spring-beans.xsd
     9        http://www.springframework.org/schema/tx
    10        http://www.springframework.org/schema/tx/spring-tx.xsd
    11        http://www.springframework.org/schema/aop
    12        http://www.springframework.org/schema/aop/spring-aop.xsd">
    13     
    14     <!-- 1、dataSource -->
    15     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    16         <property name="driverClass" value="oracle.jdbc.driver.OracleDriver"></property>
    17         <property name="jdbcUrl" value="jdbc:oracle:thin:@localhost:1521:shoreid"></property>
    18         <property name="user" value="zhangsan"></property>
    19         <property name="password" value="123456"></property>
    20         <property name="initialPoolSize" value="3"></property>
    21         <property name="maxPoolSize" value="100"></property>
    22         <property name="maxStatements" value="200"></property>
    23         <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->
    24         <property name="acquireIncrement" value="2"></property>
    25     </bean>
    26     
    27     <!-- 2、SessionFactory -->
    28     <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    29         <property name="dataSource" ref="dataSource"></property>
    30         <!-- 注入Hibernate的配置属性 -->
    31         <property name="hibernateProperties">
    32             <props>
    33                 <prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop>
    34                 <prop key="hibernate.cache.provider_class">org.hibernate.cache.NoCacheProvider</prop>
    35                 <!-- <prop key="current_session_context_class">thread</prop> -->
    36                 <prop key="hibernate.show_sql">true</prop>
    37                 <prop key="hibernate.format_sql">true</prop>
    38                 <prop key="hibernate.hbm2ddl.auto">update</prop>
    39                 <prop key="javax.persistence.validation.mode">none</prop>
    40             </props>
    41         </property>
    42         <!-- 注入注解版类 -->
    43         <property name="annotatedClasses"> <!-- name="packagesToScan" -->
    44             <list>
    45                 <value>com.oa.shore.entity.User</value>
    46                 <value>com.oa.shore.entity.Role</value>
    47                 <value>com.oa.shore.entity.Department</value>
    48             </list>
    49         </property>
    50     </bean>
    51     
    52     <!-- 3、BaseDao -->
    53     <bean id="baseDao" class="com.oa.common.dao.impl.BaseDao">
    54         <property name="sessionFactory" ref="sessionFactory"></property>
    55     </bean>
    56     
    57     
    58     <!-- 8、############Spring声明式事务管理配置########### -->
    59     <!-- 配置事务管理器 -->
    60     <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
    61         <property name="sessionFactory" ref="sessionFactory"></property>
    62     </bean>
    63     
    64     <!-- 配置事务增强(DAO) -->
    65     <!-- read:get、list、find——如果出现异常,不需要回滚
    66          update:save、delete、update——需要回滚 -->
    67     <tx:advice transaction-manager="transactionManager" id="transactionAdvice">
    68         <tx:attributes>
    69             <tx:method name="get*" read-only="true"/>
    70             <tx:method name="find*" read-only="true"/>
    71             <tx:method name="list*" read-only="true"/>
    72             <tx:method name="search*" read-only="true"/>
    73             <tx:method name="*" read-only="false" rollback-for="Throwable"/>
    74         </tx:attributes>
    75     </tx:advice>
    76     
    77     <!-- AOP配置:配置切入点表达式 -->
    78     <aop:config>  <!-- 第一个*表示返回值类型;第二个*表示service层下的所有接口实现类;第三个*表示每个接口实现类下的所有方法 -->
    79         <aop:pointcut expression="execution(* com.oa.shore.service.impl.*.*(..))" id="pt"/>
    80         <aop:advisor advice-ref="transactionAdvice" pointcut-ref="pt"/>
    81     </aop:config>
    82 </beans>

    beans_user.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     xmlns:aop="http://www.springframework.org/schema/aop"
     5     xmlns:tx="http://www.springframework.org/schema/tx"
     6     xsi:schemaLocation="
     7        http://www.springframework.org/schema/beans
     8        http://www.springframework.org/schema/beans/spring-beans.xsd
     9        http://www.springframework.org/schema/tx
    10        http://www.springframework.org/schema/tx/spring-tx.xsd
    11        http://www.springframework.org/schema/aop
    12        http://www.springframework.org/schema/aop/spring-aop.xsd">
    13     
    14     <!-- 4、entity --><!-- Action层 模型驱动用到user -->
    15     <bean id="user" class="com.oa.shore.entity.User"></bean>
    16     
    17     <!-- 5、Dao层 -->
    18     <bean id="userDao" class="com.oa.shore.dao.impl.UserDao" parent="baseDao"></bean>
    19     <bean id="roleDao" class="com.oa.shore.dao.impl.RoleDao" parent="baseDao"></bean>
    20     <bean id="departmentDao" class="com.oa.shore.dao.impl.DepartmentDao" parent="baseDao"></bean>
    21     
    22     <!-- 6、servive层 -->
    23     <bean id="userService" class="com.oa.shore.service.impl.UserService">
    24         <property name="userDao" ref="userDao"></property>
    25     </bean>
    26      <bean id="roleService" class="com.oa.shore.service.impl.RoleService">
    27         <property name="roleDao" ref="roleDao"></property>
    28     </bean>
    29     <bean id="departmentService" class="com.oa.shore.service.impl.DepartmentService">
    30         <property name="departmentDao" ref="departmentDao"></property>
    31     </bean>
    32     
    33     <!-- 7、action层 -->
    34     <bean id="userAction" class="com.oa.shore.action.UserAction">
    35         <property name="userService" ref="userService"></property>
    36         <property name="roleService" ref="roleService"></property>
    37         <property name="departmentService" ref="departmentService"></property>
    38     </bean>
    39 </beans>

    3.9、前端页面

    index.jsp

     1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
     2 <%
     3 String path = request.getContextPath();
     4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
     5 %>
     6 
     7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
     8 <html>
     9   <head>
    10     <base href="<%=basePath%>">
    11     
    12     <title>My JSP 'index.jsp' starting page</title>
    13     <meta http-equiv="pragma" content="no-cache">
    14     <meta http-equiv="cache-control" content="no-cache">
    15     <meta http-equiv="expires" content="0">    
    16     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    17     <meta http-equiv="description" content="This is my page">
    18     <!--
    19     <link rel="stylesheet" type="text/css" href="styles.css">
    20     -->
    21   </head>
    22   
    23   <body>
    24     <jsp:forward page="jsp/user/login.jsp"></jsp:forward>
    25   </body>
    26 </html>

    login.jsp

     1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
     2 <%@ taglib prefix="s" uri="/struts-tags"%>
     3 <%
     4 String path = request.getContextPath();
     5 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
     6 %>
     7 
     8 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
     9 <html>
    10   <head>
    11     <base href="<%=basePath%>">
    12     
    13     <meta http-equiv="pragma" content="no-cache">
    14     <meta http-equiv="cache-control" content="no-cache">
    15     <meta http-equiv="expires" content="0">    
    16     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    17     <meta http-equiv="description" content="This is my page">
    18     <!--
    19     <link rel="stylesheet" type="text/css" href="styles.css">
    20     -->
    21     <script type="text/javascript">
    22         function checkUser(){
    23             //检验输入的用户名和密码的合法性    省略
    24             return true;
    25         }
    26     </script>
    27 
    28   </head>
    29   
    30   <style> 
    31     table tr th{ border:1px solid #C1C1C1; font-size: 16px;}
    32     table,table tr td { border:1px solid #C1C1C1; }
    33     table {  30%; min-height: 25px; line-height: 25px; border-collapse: collapse; padding:2px; margin:auto;}
    34     a{text-decoration: none;font-weight: bold;}
    35   </style> 
    36   
    37   <body>
    38       <span><font color="red"><s:property value="errorMessage"/></font></span>
    39        <s:form name="form" action="userAction!login.action" method="post" submit="return checkUser();">
    40            <table style="align: center;">
    41                <tr>
    42                    <td style="text-align: center;">账号:</td>
    43                    <td><s:textfield name="account"></s:textfield></td>
    44                </tr>
    45                <tr>
    46                    <td style="text-align: center;">密码:</td>
    47                    <td><s:password name="password"></s:password></td>
    48                </tr>
    49            </table>
    50            <br/>
    51            <div style="text-align: center;">
    52             <s:submit name="submit" value="登录"></s:submit>&nbsp;&nbsp;&nbsp;
    53             <s:reset name="reset" value="重置"></s:reset>
    54         </div>
    55        </s:form>
    56   </body>
    57 </html>

    user-list.jsp

     1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
     2 <%@ taglib prefix="s" uri="/struts-tags"%>
     3 <%
     4 String path = request.getContextPath();
     5 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
     6 %>
     7 
     8 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
     9 <html>
    10   <head>
    11     <base href="<%=basePath%>">
    12     
    13     <title>用户列表</title>
    14     
    15     <meta http-equiv="pragma" content="no-cache">
    16     <meta http-equiv="cache-control" content="no-cache">
    17     <meta http-equiv="expires" content="0">    
    18     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    19     <meta http-equiv="description" content="This is my page">
    20     <!--
    21     <link rel="stylesheet" type="text/css" href="styles.css">
    22     -->
    23 
    24   </head>
    25   
    26   <script type="text/javascript">
    27     //全选、全反选
    28     function doSelectAll() {
    29         $("input[name='selectedRow']").prop("checked", $("#selAll").is(":checked"));
    30     }
    31   </script>
    32   
    33   <style> 
    34     table tr th{ border:1px solid #C1C1C1; font-size: 16px;}
    35     table,table tr td { border:1px solid #C1C1C1; }
    36     table {  80%; min-height: 25px; line-height: 25px; border-collapse: collapse; padding:2px; margin:auto;text-align: center;}
    37     a{text-decoration: none;font-weight: bold;}
    38   </style> 
    39   
    40   <body>
    41       <h3 align="center">用户信息列表</h3>
    42     <table>
    43         <tr style=" background-color: #EBEBEB">
    44             <th><input type="checkbox" id="selAll" onclick="doSelectAll()" /></th>
    45             <th>序号</th>
    46             <th>姓名</th>
    47             <th>账号</th>
    48             <th>所属部门</th>
    49             <th>电话</th>
    50             <th>邮箱</th>
    51             <th>操作</th>
    52         </tr>
    53            <s:if test="#request.userList != null && #request.userList.size() > 0">    
    54                <s:iterator value="userList" var="ul" status="st">
    55                 <tr>
    56                  <td><input type="checkbox" name="selectedRow" value="<s:property value='id'/>"/></td>
    57                  <td><s:property value="#st.count"/></td>
    58                  <td><s:property value="#ul.name"/></td>
    59                  <td><s:property value="#ul.account"/></td>
    60                  <td><s:property value="#ul.dept.deptName"/></td>
    61                  <td><s:property value="#ul.telphone"/></td>
    62                  <td><s:property value="#ul.email"/></td>
    63                  <td>
    64                      <s:a href="userAction-listAll.action">编辑</s:a><!-- 此功能未实现,留空,只是简单演示SSH框架(注解版) -->
    65                      <s:a href="userAction-listAll.action">删除</s:a><!-- 此功能未实现,留空,只是简单演示SSH框架(注解版) -->
    66                  </td>
    67              </tr>
    68             </s:iterator>
    69            </s:if>
    70            <s:else>
    71                <tr>
    72                    <td colspan="8">对不起,未查到任何相关信息!</td>
    73                </tr>
    74            </s:else>
    75     </table>
    76     <br/>
    77     <div style="text-align: center;">
    78         <s:a href="userAction!toAdd.action">新增用户</s:a>&nbsp;&nbsp;&nbsp;&nbsp;
    79         <s:a href="userAction-listAll.action">批量删除</s:a><!-- 此功能未实现,留空,只是简单演示SSH框架(注解版) -->
    80     </div>
    81   </body>
    82 </html>

    user-add.jsp

     1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
     2 <%@ taglib prefix="s" uri="/struts-tags"%>
     3 <%
     4 String path = request.getContextPath();
     5 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
     6 %>
     7 
     8 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
     9 <html>
    10   <head>
    11     <base href="<%=basePath%>">
    12     
    13     <title>新增用户</title>
    14     
    15     <meta http-equiv="pragma" content="no-cache">
    16     <meta http-equiv="cache-control" content="no-cache">
    17     <meta http-equiv="expires" content="0">    
    18     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    19     <meta http-equiv="description" content="This is my page">
    20     <!--
    21     <link rel="stylesheet" type="text/css" href="styles.css">
    22     -->
    23 
    24   </head>
    25   
    26   <style> 
    27     table tr th{ border:1px solid #C1C1C1; font-size: 16px;}
    28     table,table tr td { border:1px solid #C1C1C1; }
    29     th{background-color: #EBEBEB; text-align: center;}
    30     table {  50%; min-height: 25px; line-height: 25px; border-collapse: collapse; padding:2px; margin:auto;}
    31     a{text-decoration: none;font-weight: bold;}
    32   </style> 
    33   
    34   <body>
    35       <form action="<%=basePath%>userAction!save.action" method="post">
    36           <h3 align="center">新增用户</h3>
    37         <table>
    38             <tr>
    39                 <th>姓名</th>
    40                 <td><s:textfield name="name" id="name" placeholder="请输入用户名!" value="" required="true" style="45%;"></s:textfield></td>
    41             </tr>
    42             <tr>
    43                 <th>账号</th>
    44                 <td><s:textfield name="account" id="account" placeholder="请输入账号!" value="" required="true"  style="45%;"/></td>
    45             </tr>
    46             <tr>
    47                 <th>密码</th>
    48                 <td><s:password name="password" id="password" placeholder="请输入密码!" required="true"  style="45%;"/></td>
    49             </tr>
    50             <tr>
    51                 <th>所属部门</th>
    52                 <td>
    53                     <s:if test="#request.departments.size()>0">
    54                         <s:radio list="#request.departments" name="departmentId" listKey="key" listValue="value" value="550"/><br>
    55                     </s:if>
    56                     <s:else>系统内尚无任何部门,请先&nbsp;<a href="#">添加部门</a></s:else>
    57                 </td>
    58             </tr>
    59             <tr>
    60                 <th>角色名称</th>
    61                 <td>
    62                     <s:if test="#request.roles2.size()>0">
    63                            <s:checkboxlist list="#request.roles2" name="roleIds" listKey="key" listValue="value"></s:checkboxlist>
    64                        </s:if>
    65                        <s:else>系统内尚无任何角色,请先&nbsp;<a href="#">添加角色</a></s:else>
    66                 </td>
    67             </tr>
    68             <tr>
    69                 <th>电话</th>
    70                  <td><s:textfield id="telphone" name="telphone" value="" onkeyup="value=value.replace(/[^d]/g,'')"  style="45%;"/></td>
    71             </tr>
    72             <tr>
    73                 <th>邮箱</th>
    74                 <td><s:textfield id="email" name="email" value=""  style="45%;"/></td>
    75             </tr>
    76         </table>
    77         <br/>
    78         <div style="text-align: center;">
    79             <input type="submit" value="保存" />&nbsp;&nbsp;&nbsp;&nbsp;
    80             <input type="reset" value="重置" />&nbsp;&nbsp;&nbsp;&nbsp;
    81             <input type="button"  onclick="javascript:history.go(-1)" value="返回" />
    82         </div>
    83     </form>
    84   </body>
    85 </html>

    到此已完结!有任何问题,可留言。

    原创作者:DSHORE

    作者主页:http://www.cnblogs.com/dshore123/

    原文出自:https://www.cnblogs.com/dshore123/p/12336358.html

    版权声明:欢迎转载,转载务必说明出处。(如果本文对您有帮助,可以点击一下右下角的 推荐,或评论,谢谢!

  • 相关阅读:
    iOS 打电话 发邮件
    iOS
    varchar(50)能存50个汉字
    CSS 内联元素
    mysql修改用户密码的方法
    PHP error_reporting(0)
    索引数组和关联数组
    ubuntu文件夹右键没有共享选项
    Ubuntu安装samba的问题
    安卓.开发规范(高级)
  • 原文地址:https://www.cnblogs.com/dshore123/p/12336358.html
Copyright © 2020-2023  润新知