Java进阶知识30 Struts2+Spring+Hibernate+Oracle XML版整合实例

本文知识点(目录):

      1、本文整合实例最终效果图展示
      2、导读
          2.1、开发技术概述
          2.2、本项目使用的jar包、项目结构图
      3、本文所有代码(SSH:xml 版)
          3.1、Oracle 数据库建表脚本
          3.2、web.xml 配置文件
          3.3、User、Role、Department 实体类,以及对应的Hibernate配置文件
          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,采用了“xml”配置文件的方式开发;

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

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

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

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

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

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

      

3、本文所有代码(SSH:xml 版)  

3.1、Oracle 数据库建表脚本

  1 /*==============================================================*/
  2 /* DBMS name:      ORACLE Version 11g                           */
  3 /* Created on:     2020/2/23 15:33:35                           */
  4 /*==============================================================*/
  5 
  6 
  7 alter table users2
  8    drop constraint FK_USERS2_DEPARTME2;
  9 
 10 alter table users2_role2_fk
 11    drop constraint FK_USERS2_ROLE2_U;
 12 
 13 alter table users2_role2_fk
 14    drop constraint FK_ROLE2_USERS2_R;
 15 
 16 drop table department2 cascade constraints;
 17 
 18 drop table role2 cascade constraints;
 19 
 20 drop index users2_department2_fk_FK;
 21 
 22 drop table users2 cascade constraints;
 23 
 24 drop index users2_role2_fk2_FK;
 25 
 26 drop index users2_role2_fk_FK;
 27 
 28 drop table users2_role2_fk cascade constraints;
 29 
 30 /*============================================================================================*/
 31 /* Table: department2      users2表与department2表是单向多对一,users2是从表,department2是主表    */
 32 /*============================================================================================*/
 33 create table department2 
 34 (
 35    id                 INTEGER              not null,
 36    name               VARCHAR2(20),
 37    description        VARCHAR2(50),
 38    constraint PK_DEPARTMENT2 primary key (id)
 39 );
 40 
 41 /*==============================================================*/
 42 /* Table: role2      users2表与role2表是单向多对多,以users2为主表  */
 43 /*==============================================================*/
 44 create table role2 
 45 (
 46    id                 INTEGER              not null,
 47    name               VARCHAR2(20),
 48    privilege_id       INTEGER,
 49    constraint PK_ROLE2 primary key (id)
 50 );
 51 
 52 /*==============================================================*/
 53 /* Table: users2                                              */
 54 /*==============================================================*/
 55 create table users2 
 56 (
 57    id                 INTEGER              not null,
 58    department2_id     INTEGER,
 59    name               VARCHAR2(20),
 60    sex                SMALLINT,   -- 实体类设计 Boolean 类型
 61    account            VARCHAR2(20),
 62    password           VARCHAR2(32),
 63    email              VARCHAR2(20),
 64    telphone           VARCHAR2(20),
 65    constraint PK_USERS2 primary key (id)
 66 );
 67 
 68 /*==============================================================*/
 69 /* Index: users2_department2_fk_FK                              */
 70 /*==============================================================*/
 71 create index users2_department2_fk_FK on users2 (
 72    department2_id ASC
 73 );
 74 
 75 /*==============================================================*/
 76 /* Table: users2_role2_fk                                     */
 77 /*==============================================================*/
 78 create table users2_role2_fk 
 79 (
 80    users2_id           INTEGER              not null,
 81    role2_id            INTEGER              not null,
 82    constraint PK_USERS2_ROLE2_FK primary key (users2_id, role2_id)
 83 );
 84 
 85 /*==============================================================*/
 86 /* Index: users2_role2_fk_FK                                    */
 87 /*==============================================================*/
 88 create index users2_role2_fk_FK on users2_role2_fk (
 89    users2_id ASC
 90 );
 91 
 92 /*==============================================================*/
 93 /* Index: users2_role2_fk2_FK                                   */
 94 /*==============================================================*/
 95 create index users2_role2_fk2_FK on users2_role2_fk (
 96    role2_id ASC
 97 );
 98 
 99 alter table users2
100    add constraint FK_USERS2_DEPARTME2 foreign key (department2_id)
101       references department2 (id);
102 
103 alter table users2_role2_fk
104    add constraint FK_USERS2_ROLE2_U foreign key (users2_id)
105       references users2 (id);
106 
107 alter table users2_role2_fk
108    add constraint FK_ROLE2_USERS2_R foreign key (role2_id)
109       references role2 (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     <!-- struts2过滤器 begin -->
13     <filter>
14         <filter-name>struts2</filter-name>
15         <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
16     </filter>
17     <filter-mapping>
18         <filter-name>struts2</filter-name>
19         <url-pattern>/*</url-pattern>
20     </filter-mapping>
21     <!-- struts2过滤器 end -->
22       
23       <!-- spring监听器 begin-->
24       <context-param>
25         <param-name>contextConfigLocation</param-name>
26         <param-value>/WEB-INF/classes/beans_common.xml</param-value>
27     </context-param>
28     <listener>
29         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
30     </listener>
31     <!-- spring监听器 end-->
32 </web-app>

3.3、User、Role、Department 实体类,以及对应的Hibernate配置文件

User 实体类

 1 package com.shore.entity;
 2 
 3 import java.util.HashSet;
 4 import java.util.Set;
 5 
 6 /**
 7  * @author DSHORE/2020-2-23
 8  * 
 9  */
10 public class User {
11     private Integer id;
12     private Department department; //部门,department2_id (User对Department:多对一)
13     private String name;
14     private Boolean sex;
15     private String account;
16     private String password;
17     private String email;
18     private String telphone;
19     private Set<Role> roles = new HashSet<Role>(); //角色,role2_id (User对Role:多对多,以User为主)
20 
21     public Integer getId() {
22         return id;
23     }
24 
25     public void setId(Integer id) {
26         this.id = id;
27     }
28 
29     public Department getDepartment() {
30         return department;
31     }
32 
33     public void setDepartment(Department department) {
34         this.department = department;
35     }
36 
37     public String getName() {
38         return name;
39     }
40 
41     public void setName(String name) {
42         this.name = name;
43     }
44 
45     public Boolean getSex() {
46         return sex;
47     }
48 
49     public void setSex(Boolean sex) {
50         this.sex = sex;
51     }
52 
53     public String getAccount() {
54         return account;
55     }
56 
57     public void setAccount(String account) {
58         this.account = account;
59     }
60 
61     public String getPassword() {
62         return password;
63     }
64 
65     public void setPassword(String password) {
66         this.password = password;
67     }
68 
69     public String getEmail() {
70         return email;
71     }
72 
73     public void setEmail(String email) {
74         this.email = email;
75     }
76 
77     public String getTelphone() {
78         return telphone;
79     }
80 
81     public void setTelphone(String telphone) {
82         this.telphone = telphone;
83     }
84 
85     public Set<Role> getRoles() {
86         return roles;
87     }
88 
89     public void setRoles(Set<Role> roles) {
90         this.roles = roles;
91     }
92 }

User.hbm.xml 配置文件

 1 <?xml version="1.0"?>
 2 <!DOCTYPE hibernate-mapping PUBLIC
 3         "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
 4         "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
 5         
 6 <hibernate-mapping>
 7     <class name="com.shore.entity.User" table="users2">  
 8         <id name="id">
 9             <generator class="sequence">
10                 <param name="sequence">users2_seq</param>
11             </generator>
12         </id>
13         <!-- 单向 多对一 ,以User为主表-->
14         <many-to-one name="department" column="department2_id" cascade="save-update" lazy="false"/><!-- cascade:级联 -->
15         
16         <property name="name" type="java.lang.String"/> 
17         <property name="sex" type="java.lang.Boolean"/> 
18         <property name="account" type="java.lang.String"/> 
19         <property name="password" type="java.lang.String"/> 
20         <property name="email" type="java.lang.String"/> 
21         <property name="telphone" type="java.lang.String"/> 
22         
23         <!-- 单向 多对多,以User为主表 -->
24         <set name="roles" table="users2_role2_fk" cascade="save-update" lazy="false"> 
25             <key column="users2_id"/>
26             <many-to-many class="com.shore.entity.Role" column="role2_id"></many-to-many>
27         </set>
28     </class>
29 </hibernate-mapping>

Role 实体类

 1 package com.shore.entity;
 2 
 3 /**
 4  * @author DSHORE/2020-2-23
 5  * 
 6  */
 7 public class Role { //单向,多对多(Role-->User)
 8     private Integer id;
 9     private String name;
10     // 权限id,权限的实体类不写了,这里只是简单SSH框架流程(private Privilege privilege;)
11     private Integer privilege_id;
12 
13     public Integer getId() {
14         return id;
15     }
16 
17     public void setId(Integer id) {
18         this.id = id;
19     }
20 
21     public String getName() {
22         return name;
23     }
24 
25     public void setName(String name) {
26         this.name = name;
27     }
28 
29     public Integer getPrivilege_id() {
30         return privilege_id;
31     }
32 
33     public void setPrivilege_id(Integer privilege_id) {
34         this.privilege_id = privilege_id;
35     }
36 }

Role.hbm.xml 配置文件

 1 <?xml version="1.0"?>
 2 <!DOCTYPE hibernate-mapping PUBLIC
 3         "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
 4         "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
 5         
 6 <hibernate-mapping>
 7     <class name="com.shore.entity.Role" table="role2">  
 8         <id name="id">
 9             <generator class="sequence">
10                 <param name="sequence">role2_seq</param>
11             </generator>
12         </id>
13         <property name="name" type="java.lang.String"/> 
14         <property name="privilege_id" type="java.lang.Integer"/>
15     </class>
16 </hibernate-mapping>

Department 实体类

 1 package com.shore.entity;
 2 
 3 /**
 4  * @author DSHORE/2020-2-23
 5  * 
 6  */
 7 public class Department {
 8     private Integer id;
 9     private String name;
10     private String description;
11 
12     public Integer getId() {
13         return id;
14     }
15 
16     public void setId(Integer id) {
17         this.id = id;
18     }
19 
20     public String getName() {
21         return name;
22     }
23 
24     public void setName(String name) {
25         this.name = name;
26     }
27 
28     public String getDescription() {
29         return description;
30     }
31 
32     public void setDescription(String description) {
33         this.description = description;
34     }
35 }

Department.hbm.xml 配置文件

 1 <?xml version="1.0"?>
 2 <!DOCTYPE hibernate-mapping PUBLIC
 3         "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
 4         "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
 5         
 6 <hibernate-mapping>
 7     <class name="com.shore.entity.Department" table="department2">  
 8         <id name="id">
 9             <generator class="sequence">
10                 <param name="sequence">dept2_seq</param>
11             </generator>
12         </id>
13         <property name="name" type="java.lang.String"/> 
14         <property name="description" type="java.lang.String"/>
15     </class>
16 </hibernate-mapping>

3.4、dao 层

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

 1 package com.common.dao;
 2 
 3 import java.util.List;
 4 
 5 /**
 6  * @author DSHORE/2020-2-23
 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.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 
33 import com.common.dao.IBaseDao;
34 
35 /**
36  * @author DSHORE/2020-2-23
37  *
38  */
39 public class BaseDao<T> extends HibernateDaoSupport implements IBaseDao<T> {
40 
41     private Class<T> clazz;
42 
43     @SuppressWarnings("unchecked")
44     public BaseDao() {//(反射机制)构造函数的作用:获取BaseDao的子类对应的泛型的实体类对象;如:public class UserDao extends BaseDao<User>(){},获取User对象
45         Type type = this.getClass().getGenericSuperclass(); 
46         if(type instanceof ParameterizedType){
47             clazz = (Class<T>) ((ParameterizedType) type).getActualTypeArguments()[0]; 
48         }
49     }
50     
51     @Override //新增
52     public int add(T entity) {
53         return (Integer) getHibernateTemplate().save(entity);
54     }
55 
56     @SuppressWarnings("unchecked")
57     @Override //查询所有
58     public List<T> listAll() {
59         Query query = getSession().createQuery("from " + clazz.getSimpleName() + " order by id asc");
60         return query.list();
61     }
62 
63     @Override
64     public T findById(Integer id) {
65         return (T) getHibernateTemplate().get(clazz, id);
66     }
67 }

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

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

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

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

 1 package com.shore.dao;
 2 
 3 import com.common.dao.IBaseDao;
 4 import com.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.shore.dao.impl;
22 
23 import com.common.dao.impl.BaseDao;
24 import com.shore.dao.IRoleDao;
25 import com.shore.entity.Role;
26 
27 /**
28  * @author DSHORE/2020-2-20
29  *
30  */
31 public class RoleDao extends BaseDao<Role> implements IRoleDao {
32 
33 }

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

 1 package com.shore.dao;
 2 
 3 import com.common.dao.IBaseDao;
 4 import com.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.shore.dao.impl;
22 
23 import com.common.dao.impl.BaseDao;
24 import com.shore.dao.IDepartmentDao;
25 import com.shore.entity.Department;
26 
27 /**
28  * @author DSHORE/2020-2-19
29  *
30  */
31 public class DepartmentDao extends BaseDao<Department> implements IDepartmentDao {
32 
33 }

3.5、service 层

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

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

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

 1 package com.shore.service;
 2 
 3 import java.util.List;
 4 
 5 import com.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     public Role findById(Integer id);//根据id查询
16 }
17 
18 
19 /**
20  * 下面是IRoleService接口的实现类RoleService 
21  *
22  */
23 
24 
25 package com.shore.service.impl;
26 
27 import java.util.List;
28 
29 import com.shore.dao.IRoleDao;
30 import com.shore.entity.Role;
31 import com.shore.service.IRoleService;
32 
33 /**
34  * @author DSHORE/2020-2-19
35  *
36  */
37 public class RoleService implements IRoleService {
38 
39     private IRoleDao roleDao;//注入roleDao
40     public void setRoleDao(IRoleDao roleDao) {
41         this.roleDao = roleDao;
42     }
43     
44     @Override
45     public List<Role> listAll() {
46         return roleDao.listAll();
47     }
48 
49     @Override //根据id查询
50     public Role findById(Integer id) {
51         return roleDao.findById(id);
52     }
53 }

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

 1 package com.shore.service;
 2 
 3 import java.util.List;
 4 
 5 import com.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.shore.service.impl;
27 
28 import java.util.List;
29 
30 import com.shore.dao.IDepartmentDao;
31 import com.shore.entity.Department;
32 import com.shore.service.IDepartmentService;
33 
34 /**
35  * @author DSHORE/2020-2-19
36  *
37  */
38 public class DepartmentService implements IDepartmentService {
39 
40     private IDepartmentDao departmentDao;
41     public void setDepartmentDao(IDepartmentDao departmentDao) {
42         this.departmentDao = departmentDao;
43     }
44     
45     @Override
46     public List<Department> listAll() {
47         return departmentDao.listAll();
48     }
49 
50     @Override
51     public Department findById(Integer departmentId) {
52         return departmentDao.findById(departmentId);
53     }
54 
55 }

3.6、action 层(控制层:controller)

UserAction.java

  1 package com.shore.action;
  2 
  3 import java.util.ArrayList;
  4 import java.util.HashMap;
  5 import java.util.HashSet;
  6 import java.util.List;
  7 import java.util.Map;
  8 import java.util.Set;
  9 
 10 import com.shore.entity.Department;
 11 import com.shore.entity.Role;
 12 import com.opensymphony.xwork2.ActionContext;
 13 import com.opensymphony.xwork2.ActionSupport;
 14 import com.opensymphony.xwork2.ModelDriven;
 15 import com.shore.entity.User;
 16 import com.shore.service.IDepartmentService;
 17 import com.shore.service.IRoleService;
 18 import com.shore.service.IUserService;
 19 
 20 /**
 21  * @author DSHORE/2020-2-23
 22  * 
 23  */
 24 public class UserAction extends ActionSupport implements ModelDriven<User> {
 25     private static final long serialVersionUID = -8641319525033487307L;
 26 
 27     private IUserService userService;//注入userService
 28     public void setUserService(IUserService userService) {
 29         this.userService = userService;
 30     }
 31     
 32     private IDepartmentService departmentService;//注入departmentService
 33     public void setDepartmentService(IDepartmentService departmentService) {
 34         this.departmentService = departmentService;
 35     }
 36     
 37     private IRoleService roleService;//注入roleService
 38     public void setRoleService(IRoleService roleService) {
 39         this.roleService = roleService;
 40     }
 41 
 42     private User user;//模型驱动获取user对象
 43     private List<User> userList = new ArrayList<User>();//用于user-list.jsp页面显示所有用户信息
 44     private Map<Integer, String> departments = new HashMap<Integer, String>();//用于user-add.jsp页面显示所有部门
 45     private Map<Integer, String> roles2 = new HashMap<Integer, String>();//用于user-add.jsp页面显示所有角色
 46     private Integer departmentId;//用于获取user-add.jsp页面,单选框 选择哪个部门
 47     private String[] roleIds;////用于获取user-add.jsp页面,多选框 选择哪些角色
 48 
 49     private String errorMessage; // 登录时,账号/密码错误,提示信息
 50 
 51     // 登录
 52     public String login() {
 53         String account = user.getAccount().trim();
 54         String password = user.getPassword().trim();
 55         // 根据用户账号名称查询User对象
 56         User dbUser = userService.findByAccount(account);
 57         if (dbUser == null) { // 用户不存在
 58             errorMessage = "账号不存在,请重新输入!";
 59             return ERROR;
 60         } else {
 61             if (!password.equals(dbUser.getPassword())) {
 62                 errorMessage = "密码错误,请重新输入!";
 63                 return ERROR;
 64             } else {
 65                 // 把该用户(数据库中查到的)保存到session中
 66                 ActionContext.getContext().getSession()
 67                         .put("currentUser", dbUser);
 68             }
 69         }
 70         return SUCCESS;
 71     }
 72     
 73     //查询所用户信息
 74     public String listAll() {
 75         userList = userService.listAll();
 76         return "listAll";
 77     }
 78     
 79     //添加用户前,先把所有部门和所有角色查询出来,带到user-add.jsp页面,供选择
 80     public String toAdd() {
 81         List<Department> allDepartments = departmentService.listAll();
 82         if (allDepartments != null && allDepartments.size() > 0) {
 83             for (Department d : allDepartments) {
 84                 departments.put(d.getId(), d.getName());
 85             }
 86         }
 87         List<Role> allRoles = roleService.listAll();
 88         if (allRoles != null && allRoles.size() > 0) {
 89             for (Role r : allRoles) {
 90                 roles2.put(r.getId(), r.getName());
 91             }
 92         }
 93         return "toAdd";
 94     }
 95     
 96     //新增用户
 97     public String save() {
 98         if (user != null) {
 99             //部门
100             if (departmentId != null) {
101                 user.setDepartment(departmentService.findById(departmentId));
102             }
103             //角色
104             Set<Role> roleSet = new HashSet<Role>();
105             if (roleIds != null && roleIds.length > 0) {
106                 for (String id : roleIds) {
107                     Role role = roleService.findById(Integer.parseInt(id));
108                     roleSet.add(role);
109                 }
110             }
111             user.setRoles(roleSet);
112             userService.add(user);
113         }
114         return "success";
115     }
116         
117 
118     @Override //模型驱动获取user对象
119     public User getModel() {
120         return user;
121     }
122 
123     public User getUser() {
124         return user;
125     }
126 
127     public void setUser(User user) {
128         this.user = user;
129     }
130 
131     public String getErrorMessage() {
132         return errorMessage;
133     }
134 
135     public void setErrorMessage(String errorMessage) {
136         this.errorMessage = errorMessage;
137     }
138 
139     public List<User> getUserList() {
140         return userList;
141     }
142 
143     public void setUserList(List<User> userList) {
144         this.userList = userList;
145     }
146 
147     public Map<Integer, String> getDepartments() {
148         return departments;
149     }
150 
151     public void setDepartments(Map<Integer, String> departments) {
152         this.departments = departments;
153     }
154 
155     public Map<Integer, String> getRoles2() {
156         return roles2;
157     }
158 
159     public void setRoles2(Map<Integer, String> roles2) {
160         this.roles2 = roles2;
161     }
162 
163     public Integer getDepartmentId() {
164         return departmentId;
165     }
166 
167     public void setDepartmentId(Integer departmentId) {
168         this.departmentId = departmentId;
169     }
170 
171     public String[] getRoleIds() {
172         return roleIds;
173     }
174 
175     public void setRoleIds(String[] roleIds) {
176         this.roleIds = roleIds;
177     }
178 }

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.shore.action.UserAction">
15             <result name="success" type="redirectAction">userAction!listAll.action</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.LocalSessionFactoryBean">
 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="hibernate.show_sql">true</prop>
 36                 <prop key="hibernate.format_sql">true</prop>
 37                 <prop key="hibernate.hbm2ddl.auto">update</prop>
 38                 <prop key="javax.persistence.validation.mode">none</prop>
 39             </props>
 40         </property>
 41         <!-- 注入xml配置文件 -->
 42         <property name="mappingLocations"> 
 43             <list>
 44                 <value>classpath:com/shore/entity/*.hbm.xml</value>
 45                 <!-- <value>classpath:com/shore/entity/Role.hbm.xml</value>
 46                 <value>classpath:com/shore/entity/Department.hbm.xml</value> -->
 47             </list>
 48         </property>
 49     </bean>
 50     
 51     <!-- 3、BaseDao -->
 52     <bean id="baseDao" class="com.common.dao.impl.BaseDao">
 53         <property name="sessionFactory" ref="sessionFactory"></property>
 54     </bean>
 55     
 56     <!-- 4、entity --><!-- Action层 模型驱动用到user -->
 57     <bean id="user" class="com.shore.entity.User"></bean>
 58     
 59     <!-- 5、Dao层 -->
 60     <bean id="userDao" class="com.shore.dao.impl.UserDao" parent="baseDao"></bean>
 61     <bean id="roleDao" class="com.shore.dao.impl.RoleDao" parent="baseDao"></bean>
 62     <bean id="departmentDao" class="com.shore.dao.impl.DepartmentDao" parent="baseDao"></bean>
 63     
 64     <!-- 6、servive层 -->
 65     <bean id="userService" class="com.shore.service.impl.UserService">
 66         <property name="userDao" ref="userDao"></property>
 67     </bean>
 68     <bean id="roleService" class="com.shore.service.impl.RoleService">
 69         <property name="roleDao" ref="roleDao"></property>
 70     </bean>
 71     <bean id="departmentService" class="com.shore.service.impl.DepartmentService">
 72         <property name="departmentDao" ref="departmentDao"></property>
 73     </bean>
 74     
 75     <!-- 7、action层 -->
 76     <bean id="userAction" class="com.shore.action.UserAction">
 77         <property name="userService" ref="userService"></property>
 78         <property name="roleService" ref="roleService"></property>
 79         <property name="departmentService" ref="departmentService"></property>
 80     </bean>
 81     
 82     
 83     <!-- 8、############Spring声明式事务管理配置########### -->
 84     <!-- 配置事务管理器 -->
 85     <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
 86         <property name="sessionFactory" ref="sessionFactory"></property>
 87     </bean>
 88     
 89     <!-- 配置事务增强(DAO) -->
 90     <!-- read:get、list、find——如果出现异常,不需要回滚
 91          update:save、delete、update——需要回滚 -->
 92     <tx:advice transaction-manager="transactionManager" id="transactionAdvice">
 93         <tx:attributes>
 94             <tx:method name="get*" read-only="true"/>
 95             <tx:method name="find*" read-only="true"/>
 96             <tx:method name="list*" read-only="true"/>
 97             <tx:method name="search*" read-only="true"/>
 98             <tx:method name="*" read-only="false" rollback-for="Throwable"/>
 99         </tx:attributes>
100     </tx:advice>
101     
102     <!-- AOP配置:配置切入点表达式 -->
103     <aop:config>  <!-- 第一个*表示返回值类型;第二个*表示service层下的所有接口实现类;第三个*表示每个接口实现类下的所有方法 -->
104         <aop:pointcut expression="execution(* com.shore.service.impl.*.*(..))" id="pt"/>
105         <aop:advisor advice-ref="transactionAdvice" pointcut-ref="pt"/>
106     </aop:config>
107 </beans>

3.9、前端页面

index.jsp

 1 <%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
 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 { width: 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 { width: 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             <th>操作</th>
53         </tr>
54            <s:if test="#request.userList != null && #request.userList.size() > 0">    
55                <s:iterator value="userList" var="ul" status="st">
56                 <tr>
57                  <td><input type="checkbox" name="selectedRow" value="<s:property value='id'/>"/></td>
58                  <td><s:property value="#st.count"/></td>
59                  <td><s:property value="#ul.name"/></td>
60                  <td>
61                      <s:if test="#ul.sex==true"></s:if>
62                     <s:elseif test="#ul.sex==false"></s:elseif> 
63                     <s:else>--</s:else>
64                  </td>
65                  <td><s:property value="#ul.account"/></td>
66                  <td><s:property value="#ul.department.name"/></td>
67                  <td><s:property value="#ul.telphone"/></td>
68                  <td><s:property value="#ul.email"/></td>
69                  <td>
70                      <s:a href="userAction-listAll.action">编辑</s:a><!-- 此功能未实现,留空,简单演示SSH框架(xml版) -->
71                      <s:a href="userAction-listAll.action">删除</s:a><!-- 此功能未实现,留空,简单演示SSH框架(xml版) -->
72                  </td>
73              </tr>
74             </s:iterator>
75            </s:if>
76            <s:else>
77                <tr>
78                    <td colspan="9">对不起,未查到任何相关信息!</td>
79                </tr>
80            </s:else>
81     </table>
82     <br/>
83     <div style="text-align: center;">
84         <s:a href="userAction!toAdd.action">新增用户</s:a>&nbsp;&nbsp;&nbsp;&nbsp;
85         <s:a href="userAction-listAll.action">批量删除</s:a><!-- 此功能未实现,留空,简单演示SSH框架(xml版) -->
86     </div>
87   </body>
88 </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 { width: 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="width:45%;"></s:textfield></td>
41             </tr>
42             <tr>
43                 <th>性别</th>
44                 <td><s:radio list="#{'true':'男','false':'女'}" name="sex" value="true"/></td>
45             </tr>
46             <tr>
47                 <th>账号</th>
48                 <td><s:textfield name="account" id="account" placeholder="请输入账号!" value="" required="true"  style="width:45%;"/></td>
49             </tr>
50             <tr>
51                 <th>密码</th>
52                 <td><s:password name="password" id="password" placeholder="请输入密码!" required="true"  style="width:45%;"/></td>
53             </tr>
54             <tr>
55                 <th>所属部门</th>
56                 <td>
57                     <s:if test="#request.departments.size()>0">
58                         <s:radio list="#request.departments" name="departmentId" listKey="key" listValue="value" value="10"/><br>
59                     </s:if>
60                     <s:else>系统内尚无任何部门,请先&nbsp;<a href="#">添加部门</a></s:else>
61                 </td>
62             </tr>
63             <tr>
64                 <th>角色名称</th>
65                 <td>
66                     <s:if test="#request.roles2.size()>0">
67                            <s:checkboxlist list="#request.roles2" name="roleIds" listKey="key" listValue="value"></s:checkboxlist>
68                        </s:if>
69                        <s:else>系统内尚无任何角色,请先&nbsp;<a href="#">添加角色</a></s:else>
70                 </td>
71             </tr>
72             <tr>
73                 <th>电话</th>
74                  <td><s:textfield id="telphone" name="telphone" placeholder="请输入电话号码!" value="" onkeyup="value=value.replace(/[^\d]/g,'')"  style="width:45%;"/></td>
75             </tr>
76             <tr>
77                 <th>邮箱</th>
78                 <td><s:textfield id="email" name="email" placeholder="请输入邮箱!" value=""  style="width:45%;"/></td>
79             </tr>
80         </table>
81         <br/>
82         <div style="text-align: center;">
83             <input type="submit" value="保存" />&nbsp;&nbsp;&nbsp;&nbsp;
84             <input type="reset" value="重置" />&nbsp;&nbsp;&nbsp;&nbsp;
85             <input type="button"  onclick="javascript:history.go(-1)" value="返回" />
86         </div>
87     </form>
88   </body>
89 </html>

 

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

 

 

 

 

 

 

 

原创作者:DSHORE

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

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

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

posted @ 2020-02-23 20:51  DSHORE  阅读(343)  评论(0编辑  收藏  举报