Java进阶知识37 Spring+SpringMVC+mybatis+Oracle【xml版】

本文知识点(目录):

      1、本文整合实例最终效果图展示
      2、导读
          2.1、开发技术概述
          2.2、本项目使用的jar包、项目结构图
      3、本文所有代码(xml 版)
          3.1、Oracle 数据库建表脚本
          3.2、web.xml 配置文件
          3.3、mybatis.xml 配置文件
          3.4、实体类及配置文件
          3.5、dao 层
          3.6、service 层
          3.7、controller 控制层/器
          3.8、Spring 配置文件(beans.xml)
          3.9、SpringMVC核心配置文件
          3.10、前端页面



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

数据库表

前端

2、导读                    

2.1、开发技术概述

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

    b.本文只实现了用户登录(含账号查询)、查询所有(用户、部门、角色);

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

    d.注意:如果查询两张表,或多张表时,出现相同字段名,不同表,但是查询到的值是同一张表的值的解决方法:https://blog.csdn.net/lee4037/article/details/16798941

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

    

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

3.1、Oracle 数据库建表脚本

 1 -- Create Table: department 
 2 -- users表与department表是单向多对一,users是从表,department是主表 
 3 create table department (
 4    id            NUMBER(6)      primary key,
 5    name          VARCHAR2(20),
 6    description   VARCHAR2(50)
 7 );
 8 
 9 -- Create Table: role 
10 -- users表与role表是单向多对多,以users为主表   
11 create table role (
12    id            NUMBER(6)      primary key,
13    name          VARCHAR2(20),
14    privilege_id  NUMBER(6)
15 );
16 
17 -- Create Table: users
18 create table users (
19    id            NUMBER(6)      primary key,
20    department_id NUMBER(6),
21    name          VARCHAR2(20),
22    sex             NUMBER(1),
23    account       VARCHAR2(20),
24    password      VARCHAR2(32),
25    email         VARCHAR2(20),
26    telphone      VARCHAR2(20),
27    flag             NUMBER(1),
28    constraint users_department_fk foreign key (department_id) references department (id)
29 );
30 
31 -- Create Table: users_role
32 create table users_role 
33 (
34    users_id      NUMBER(6)      not null,
35    role_id       NUMBER(6)      not null,
36    constraint users_role_pk primary key (users_id, role_id),
37    constraint users_role_fk foreign key (users_id) references users (id),
38    constraint role_users_fk foreign key (role_id) references role (id)
39 );
40 
41 -- 创建对应表的【序列】
42 create sequence users_seq
43 minvalue 1    
44 maxvalue 999999    
45 start with 1 
46 increment by 1;
47 
48 create sequence department_seq
49 minvalue 1    
50 maxvalue 999999    
51 start with 1 
52 increment by 1;
53 
54 create sequence role_seq
55 minvalue 1    
56 maxvalue 999999    
57 start with 1 
58 increment by 1;
59 
60 -- 创建对应表和序列的【触发器】
61 -- 触发器需要一个一个的创建,同时创建,虽然没报错,但是不会成功(Developer工具)。
62 create or replace trigger users_tg
63   before insert on users for each row 
64     begin
65       select users_seq.Nextval into:new.id from dual;
66   end;
67 
68 create or replace trigger department_tg
69   before insert on department for each row 
70     begin
71       select department_seq.Nextval into:new.id from dual;
72   end;
73 
74 create or replace trigger role_tg
75   before insert on role for each row 
76     begin
77       select role_seq.Nextval into:new.id from dual;
78   end;
79 
80 -- 手动插入数据
81 insert into department(name,description) values('人事部','hr');
82 insert into department(name,description) values('财务部','财务');
83 insert into department(name,description) values('软件开发部','软件开发');
84 
85 insert into users(name,sex,account,password,department_id,flag) values('张三',1,'zhangsan','123456',1,1);
86 insert into users(name,sex,account,password,department_id,flag) values('李四',0,'lisi','123456',3,0);
87 insert into users(name,sex,account,password,department_id,flag) values('王五',1,'wangwu','123456',2,1);
88 insert into users(name,sex,account,password,department_id,flag) values('赵六',1,'zhaoliu','123456',3,1);
89 
90 insert into role(name,privilege_id) values('超级管理员',2);
91 insert into role(name,privilege_id) values('财务部管理员',3);
92 insert into role(name,privilege_id) values('普通管理员',1);
93 
94 -- 中间表
95 insert into users_role values(1,1);
96 insert into users_role values(2,1);
97 insert into users_role values(2,2);
98 insert into users_role values(3,3);

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监听 -->
13       <context-param>
14         <param-name>contextConfigLocation</param-name>
15         <param-value>classpath:conf/beans.xml</param-value>
16     </context-param>
17     <listener>
18         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
19     </listener>
20     
21     <!-- springmvc核心控制器 -->
22     <servlet>
23         <servlet-name>DispatcherServlet</servlet-name>
24         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
25         <init-param>
26             <param-name>contextConfigLocation</param-name>
27             <param-value>classpath:conf/springmvc.xml</param-value>
28             <!-- classpath: 等价于WEB-INF/classes/ -->
29         </init-param>
30     </servlet>
31     <servlet-mapping>
32         <servlet-name>DispatcherServlet</servlet-name>
33         <url-pattern>*.action</url-pattern>
34     </servlet-mapping>
35     
36     <!-- 编码过滤器 -->
37     <filter>
38         <filter-name>CharacterEncodingFilter</filter-name>
39         <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
40         <init-param>
41             <param-name>encoding</param-name>
42             <param-value>UTF-8</param-value>
43         </init-param>
44     </filter>
45     <filter-mapping>
46         <filter-name>CharacterEncodingFilter</filter-name>
47         <url-pattern>/*</url-pattern>
48     </filter-mapping>
49 </web-app>

3.3、mybatis.xml 配置文件

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
 3 "http://mybatis.org/dtd/mybatis-3-config.dtd">
 4 <configuration>
 5     <!-- <environments default="development">
 6         <environment id="development">
 7             <transactionManager type="JDBC" />
 8             <dataSource type="POOLED">
 9                 <property name="driver" value="oracle.jdbc.driver.OracleDriver" />
10                 <property name="url" value="jdbc:oracle:thin:@localhost:1521:shoreid" />
11                 <property name="username" value="zhangsan" />
12                 <property name="password" value="123456" />
13             </dataSource>
14         </environment>
15     </environments> -->
16 
17     <mappers>
18         <mapper resource="com/shore/entity/DepartmentMapper.xml"/>
19         <mapper resource="com/shore/entity/UserMapper.xml"/>
20         <mapper resource="com/shore/entity/RoleMapper.xml"/>
21     </mappers>
22 </configuration>

3.4、实体类及配置文件

User.java 实体类

 1 package com.shore.entity;
 2 
 3 import java.util.List;
 4 
 5 /**
 6  * @author DSHORE/2020-3-27
 7  * 
 8  */
 9 public class User {
10     private Integer id;
11     private String name;
12     private Integer sex; //1代表“男”;0代表“女”
13     private String account;
14     private String password;
15     private String email;
16     private String telphone;
17     private Integer flag; //1代表“有效”;0代表女“无效”
18     private Department department; //单向多对一;user为多的一方
19     private List<Role> roles; //单向多对多;以user为主
20 
21     //省略了Setter和Getter和toString()方法
22 }

Department.java 实体类

 1 package com.shore.entity;
 2 
 3 import java.util.List;
 4 
 5 /**
 6  * @author DSHORE/2020-3-27
 7  * 
 8  */
 9 public class Department {
10     private Integer id;
11     private String name;
12     private String description;
13     private List<User> users;
14 
15     //省略了Setter和Getter和toString()方法
16 }

Role.java 实体类

 1 package com.shore.entity;
 2 
 3 import java.util.List;
 4 
 5 /**
 6  * @author DSHORE/2020-3-27
 7  * 
 8  */
 9 public class Role {
10     private Integer id;
11     private String name;
12     // 权限id,权限的实体类不写了,这里只是简单SSM框架流程
13     // 数据库没创建权限表
14     private Integer privilege_id;
15     private List<User> users; //单向多对多;以user为主
16 
17     //省略了Setter和Getter和toString()方法
18 }

UserRoleLink.java 实体类

 1 package com.shore.entity;
 2 
 3 /**
 4  * @author DSHORE/2020-3-27
 5  * UserRoleLink维护User和Role之间的关联关系
 6  */
 7 public class UserRoleLink {//User和Role:多对多
 8     private User user;
 9     private Role role;
10 
11     //省略了Setter和Getter方法
12 }

UserMapper.xml 配置文件

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 3 "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 4 
 5 <mapper namespace="userNameSpace">
 6     <resultMap id="userResultMap" type="com.shore.entity.User">
 7         <id property="id" column="id"/>
 8         <result property="name" column="name"/>
 9         <result property="sex" column="sex"/>
10         <result property="account" column="account"/>
11         <result property="password" column="password"/>
12         <result property="email" column="email"/>
13         <result property="telphone" column="telphone"/>
14         <result property="flag" column="flag"/>
15             <!-- 多对一:一个部门对应多个用户,user是多的一方 -->
16             <association property="department" column="department_id" javaType="com.shore.entity.Department">
17                 <id property="id" column="dept_id"/>
18                 <result property="name" column="dept_name"/>
19                 <result property="description" column="description"/>
20             </association>
21             <!-- 一对多:一个用户,可以有多个角色 -->
22             <collection property="roles" ofType="com.shore.entity.Role" javaType="java.util.ArrayList">
23                 <id property="id" column="role_id"/>
24                 <result property="name" column="role_name"/>
25                 <result property="privilege_id" column="privilege_id"/>
26             </collection>
27     </resultMap>
28     
29     <!-- 查询所有 -->
30     <select id="listAll" resultMap="userResultMap">
31         select u.*,d.id dept_id,d.name dept_name,d.description,r.id role_id,r.name role_name,r.privilege_id  
32         from users u,department d,users_role ur,role r
33         where u.department_id = d.id and ur.users_id = role_id
34     </select>
35     
36     <!-- 根据账号查询 -->
37     <select id="findByAccount" parameterType="String" resultMap="userResultMap">
38         select * from users where account=#{account}
39     </select>
40 </mapper>

DepartmentMapper.xml 配置文件

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 3 "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 4 
 5 <mapper namespace="departmentNameSpace">
 6     <resultMap id="departmentResultMap" type="com.shore.entity.Department">
 7         <id property="id" column="id"/>
 8         <result property="name" column="name"/>
 9         <result property="description" column="description"/>
10             <!-- 一对多:一个部门有多个用户/员工,department是一的一方 -->
11             <collection property="users" ofType="com.shore.entity.User" javaType="java.util.ArrayList">
12                 <id property="id" column="id"/>
13                 <result property="name" column="name"/>
14                 <result property="sex" column="sex"/>
15                 <result property="account" column="account"/>
16                 <result property="password" column="password"/>
17                 <result property="email" column="email"/>
18                 <result property="telphone" column="telphone"/>
19                 <result property="flag" column="flag"/>
20             </collection>
21     </resultMap>
22     
23     <!-- 查询所有 -->
24     <select id="listAll" parameterType="java.util.Map" resultMap="departmentResultMap">
25         select * from department
26     </select>
27 </mapper>

RoleMapper.xml 配置文件

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 3 "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 4 
 5 <mapper namespace="roleNameSpace">
 6     <resultMap id="roleResultMap" type="com.shore.entity.Role">
 7         <id property="id" column="id"/>
 8         <result property="name" column="name"/>
 9         <result property="privilege_id" column="privilege_id"/>
10         <!-- 一对多:一个角色,可以有多个用户 -->
11         <collection property="users" ofType="com.shore.entity.User" javaType="java.util.ArrayList">
12             <id property="id" column="id"/>
13             <result property="name" column="name"/>
14             <result property="sex" column="sex"/>
15             <result property="account" column="account"/>
16             <result property="password" column="password"/>
17             <result property="email" column="email"/>
18             <result property="telphone" column="telphone"/>
19             <result property="flag" column="flag"/>
20         </collection>
21         <!-- <collection property="users" column="id" resultMap="userNameSpace.userResultMap"></collection> -->
22     </resultMap>
23     
24     <!-- 查询所有 -->
25     <select id="listAll" resultMap="roleResultMap">
26         select * from role
27     </select>
28 </mapper>

3.5、dao 层

接口类 IUserDao 及其实现类 UserDao

 1 package com.shore.dao;
 2 
 3 import java.util.List;
 4 
 5 import com.shore.entity.User;
 6 
 7 /**
 8  * @author DSHORE/2020-3-27
 9  *
10  */
11 public interface IUserDao {//接口类
12     public List<User> listAll();
13     
14     public User findByAccount(String account);
15 }
16 
17 
18 /**
19  * 下面是 IUserDao 接口类的实现类 UserDao
20  */
21 
22 
23 package com.shore.dao.impl;
24 
25 import java.util.ArrayList;
26 import java.util.List;
27 
28 import org.apache.ibatis.session.SqlSession;
29 import org.apache.ibatis.session.SqlSessionFactory;
30 import org.springframework.beans.factory.annotation.Autowired;
31 
32 import com.shore.dao.IUserDao;
33 import com.shore.entity.User;
34 
35 /**
36  * @author DSHORE/2020-3-27
37  *
38  */
39 public class UserDao implements IUserDao {
40 
41     @Autowired
42     private SqlSessionFactory sqlSessionFactory;
43     public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
44         this.sqlSessionFactory = sqlSessionFactory;
45     }
46     
47     @Override
48     public List<User> listAll() {
49         List<User> users = new ArrayList<User>();
50         SqlSession sqlSession = sqlSessionFactory.openSession();
51         users = sqlSession.selectList("userNameSpace.listAll");
52         sqlSession.close();
53         return users;
54     }
55 
56     @Override
57     public User findByAccount(String account) {
58         List<User> users = new ArrayList<User>();
59         SqlSession sqlSession = sqlSessionFactory.openSession();
60         users = sqlSession.selectList("userNameSpace.findByAccount", account);
61         sqlSession.close();
62         if (users != null && users.size() > 0) {
63             return users.get(0);
64         }
65         return null;
66     }
67 }

接口类 IDepartmentDao 及其实现类 DepartmentDao

 1 package com.shore.dao;
 2 
 3 import java.util.List;
 4 
 5 import com.shore.entity.Department;
 6 
 7 /**
 8  * @author DSHORE/2020-3-27
 9  *
10  */
11 public interface IDepartmentDao {
12     public List<Department> listAll();
13 }
14 
15 
16 /**
17  * 下面是 IDepartmentDao 接口类的实现类 DepartmentDao 
18  *
19  */
20 
21 
22 package com.shore.dao.impl;
23 
24 import java.util.ArrayList;
25 import java.util.List;
26 
27 import org.apache.ibatis.session.SqlSession;
28 import org.apache.ibatis.session.SqlSessionFactory;
29 import org.springframework.beans.factory.annotation.Autowired;
30 
31 import com.shore.dao.IDepartmentDao;
32 import com.shore.entity.Department;
33 
34 /**
35  * @author DSHORE/2020-3-27
36  *
37  */
38 public class DepartmentDao implements IDepartmentDao {
39 
40     @Autowired
41     private SqlSessionFactory sqlSessionFactory;
42     public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
43         this.sqlSessionFactory = sqlSessionFactory;
44     }
45     
46     @Override
47     public List<Department> listAll() {
48         List<Department> departments = new ArrayList<Department>();
49         SqlSession sqlSession = sqlSessionFactory.openSession();
50         departments = sqlSession.selectList("departmentNameSpace.listAll");
51         sqlSession.close();
52         return departments;
53     }
54 }

接口类 IRoleDao 及其实现类 RoleDao

 1 package com.shore.dao;
 2 
 3 import java.util.List;
 4 
 5 import com.shore.entity.Role;
 6 
 7 /**
 8  * @author DSHORE/2020-3-27
 9  *
10  */
11 public interface IRoleDao {
12     public List<Role> listAll();
13 }
14 
15 
16 /**
17  * 下面是 IRoleDao 接口类的实现类 RoleDao 
18  *
19  */
20 
21 
22 package com.shore.dao.impl;
23 
24 import java.util.ArrayList;
25 import java.util.List;
26 
27 import org.apache.ibatis.session.SqlSession;
28 import org.apache.ibatis.session.SqlSessionFactory;
29 import org.springframework.beans.factory.annotation.Autowired;
30 
31 import com.shore.dao.IRoleDao;
32 import com.shore.entity.Role;
33 
34 /**
35  * @author DSHORE/2020-3-27
36  *
37  */
38 public class RoleDao implements IRoleDao {
39 
40     @Autowired
41     private SqlSessionFactory sqlSessionFactory;
42     public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
43         this.sqlSessionFactory = sqlSessionFactory;
44     }
45     
46     @Override
47     public List<Role> listAll() {
48         List<Role> roles = new ArrayList<Role>();
49         SqlSession sqlSession = sqlSessionFactory.openSession();
50         roles = sqlSession.selectList("roleNameSpace.listAll");
51         sqlSession.close();
52         return roles;
53     }
54 }

3.6、service 层

接口类 IUserService 及其实现类 UserService

 1 package com.shore.service;
 2 
 3 import com.shore.entity.User;
 4 
 5 /**
 6  * @author DSHORE/2020-3-27
 7  *
 8  */
 9 public interface IUserService {
10     public User findByAccount(String account);
11 }
12 
13 
14 /**
15  * 下面是 IUserService 接口类的实现类 UserService 
16  *
17  */
18 
19 
20 package com.shore.service.impl;
21 
22 import org.springframework.beans.factory.annotation.Autowired;
23 
24 import com.shore.dao.IUserDao;
25 import com.shore.entity.User;
26 import com.shore.service.IUserService;
27 
28 /**
29  * @author DSHORE/2020-3-27
30  *
31  */
32 public class UserService implements IUserService {
33 
34     @Autowired
35     private IUserDao userDao;
36     public void setUserDao(IUserDao userDao) {
37         this.userDao = userDao;
38     }
39 
40     @Override
41     public User findByAccount(String account) {
42         return userDao.findByAccount(account);
43     }
44 }

3.7、controller 控制层/器

 1 package com.shore.action;
 2 
 3 import org.springframework.beans.factory.annotation.Autowired;
 4 import org.springframework.stereotype.Controller;
 5 import org.springframework.ui.Model;
 6 import org.springframework.web.bind.annotation.RequestMapping;
 7 
 8 import com.shore.entity.User;
 9 import com.shore.service.IUserService;
10 
11 /**
12  * @author DSHORE/2020-3-27
13  *
14  */
15 @Controller
16 @RequestMapping(value="userAction")
17 public class UserAction {
18     @Autowired //自动装配:@Autowired可以对成员变量、方法和构造函数进行标注,来完成自动装配的工作
19     private IUserService userService;
20 
21     public void setUserService(IUserService userService) {
22         this.userService = userService;
23     }
24     
25     //用户登录
26     @RequestMapping(value = "/login.action")
27     public String login(Model model, User user) {
28         String account = user.getAccount().trim();
29         String password = user.getPassword().trim();
30         User dbUser = userService.findByAccount(account);
31         if (dbUser != null) {
32             if (dbUser.getFlag().equals(1)) { //有效用户
33                 if (password.equals(dbUser.getPassword())) {
34                     model.addAttribute("message", "登录成功!");
35                     return "success";
36                 } else {
37                     model.addAttribute("message", "密码错误,请重新登录!");
38                     return "error";
39                 }
40             } else {
41                 model.addAttribute("message", "该用户已被注销,请联系管理员!");
42                 return "error";
43             }
44         } else {
45             model.addAttribute("message", "账号错误,请重新登录!");
46             return "error";
47         }
48     }
49 }

3.8、Spring 配置文件(beans.xml)

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
 4     xmlns:tx="http://www.springframework.org/schema/tx"
 5     xsi:schemaLocation="
 6        http://www.springframework.org/schema/beans
 7        http://www.springframework.org/schema/beans/spring-beans.xsd
 8        http://www.springframework.org/schema/tx
 9        http://www.springframework.org/schema/tx/spring-tx.xsd
10        http://www.springframework.org/schema/aop
11        http://www.springframework.org/schema/aop/spring-aop.xsd">
12 
13     <!-- 1、dataSource -->
14     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
15         <property name="driverClass" value="oracle.jdbc.driver.OracleDriver"></property>
16         <property name="jdbcUrl" value="jdbc:oracle:thin:@localhost:1521:shoreid"></property>
17         <property name="user" value="zhangsan"></property>
18         <property name="password" value="123456"></property>
19     </bean>
20     
21     <!-- 2、创建SqlSessionFactory的bean,把dataSource注入其中 -->
22     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
23         <property name="dataSource" ref="dataSource"></property>
24         <property name="configLocation" value="classpath:conf/mybatis.xml"/>
25     </bean>
26     
27     <!-- 3、注入DAO -->
28     <bean id="userDao" class="com.shore.dao.impl.UserDao">
29         <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
30     </bean>
31     <bean id="roleDao" class="com.shore.dao.impl.RoleDao">
32         <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
33     </bean>
34     <bean id="departmentDao" class="com.shore.dao.impl.DepartmentDao">
35         <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
36     </bean>
37     
38     <!-- 4、注入Service -->
39     <bean id="userService" class="com.shore.service.impl.UserService">
40         <property name="userDao" ref="userDao"></property>
41     </bean>
42     
43     <!-- 5、注入Action -->
44     <bean id="userAction" class="com.shore.action.UserAction">
45         <property name="userService" ref="userService"></property>
46     </bean>
47     
48     <!-- ============== 6、配置事务管理 ============== -->
49     <!-- 事务管理  -->
50     <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
51         <property name="dataSource" ref="dataSource"></property>
52     </bean>
53     
54     <!-- 配置事务增强(DAO) -->
55     <!-- read:get、list、find——如果出现异常,不需要回滚
56     update:save、delete、update——需要回滚 -->
57     <tx:advice transaction-manager="transactionManager" id="transactionAdvice">
58         <tx:attributes>
59             <tx:method name="get*" read-only="true"/>
60             <tx:method name="find*" read-only="true"/>
61             <tx:method name="list*" read-only="true"/>
62             <tx:method name="search*" read-only="true"/>
63             <tx:method name="*" read-only="false" rollback-for="Throwable"/>
64         </tx:attributes>
65     </tx:advice>
66     
67     <!-- AOP配置:配置切入点表达式 -->
68     <aop:config>
69         <aop:pointcut expression="execution(* com.shore.dao.impl.*.*(..))" id="pt"/>
70         <aop:advisor advice-ref="transactionAdvice" pointcut-ref="pt"/>
71     </aop:config>
72 </beans>

3.9、SpringMVC核心配置文件

 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     xmlns:context="http://www.springframework.org/schema/context"
 7     xsi:schemaLocation="
 8        http://www.springframework.org/schema/beans
 9        http://www.springframework.org/schema/beans/spring-beans.xsd
10        http://www.springframework.org/schema/mvc
11        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
12        http://www.springframework.org/schema/context
13        http://www.springframework.org/schema/context/spring-context-3.0.xsd">
14     
15     <!-- 1、映射器(可选) -->
16     <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"></bean>
17     
18     <!-- 2、适配器(可选) -->
19     <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"></bean>
20     
21     <!-- 3、控制器 -->
22     <context:component-scan base-package="com.shore.action"/>
23     
24     <!-- 4、视图解析器(可选,如果写了视图逻辑名,就必须要配置) -->
25     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
26         <property name="prefix" value="/"></property>
27         <property name="suffix" value=".jsp"></property>
28     </bean>
29 </beans>

3.10、前端页面
index.jsp

1 <body>
2     <jsp:forward page="login.jsp"></jsp:forward>
3 </body>

success.jsp 和 error.jsp 内容一样

1 <body>
2     ${message}
3 </body>

login.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 'login.jsp' starting page</title>
13     
14     <meta http-equiv="pragma" content="no-cache">
15     <meta http-equiv="cache-control" content="no-cache">
16     <meta http-equiv="expires" content="0">    
17     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
18     <meta http-equiv="description" content="This is my page">
19     <!--
20     <link rel="stylesheet" type="text/css" href="styles.css">
21     -->
22 
23   </head>
24   <style> 
25        table tr th{ border:1px solid #C1C1C1; font-size: 16px;}
26        table,table tr td { border:1px solid #C1C1C1; }
27        table { width: 30%; min-height: 25px; line-height: 25px; border-collapse: collapse; padding:2px; margin:auto;}
28        a{text-decoration: none;font-weight: bold;}
29   </style>
30    
31   <body>
32        <form action="userAction/login.action" method="post">
33         <table>
34             <tr>
35                 <td align="center">账号</td>
36                 <td><input type="text" name="account" value="" style="width: 60%"/></td>
37             </tr>
38                <tr>
39                 <td align="center">密码</td>
40                 <td><input type="password" name="password" value="" style="width: 60%"/></td>
41             </tr>
42                <tr>
43                 <td colspan="2" align="center">
44                     <input type="submit" name="submit" value="登录"/>&nbsp;&nbsp;
45                     <input type="reset" name="reset" value="取消"/>
46                 </td>
47             </tr>
48         </table>
49      </form>
50   </body>
51 </html>

 

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

 

 附录 

dao层,测试类代码(UserDaoTest)

 1 package test;
 2 
 3 import java.util.List;
 4 
 5 import org.junit.Test;
 6 import org.springframework.context.ApplicationContext;
 7 import org.springframework.context.support.ClassPathXmlApplicationContext;
 8 
 9 import com.shore.dao.IDepartmentDao;
10 import com.shore.dao.IRoleDao;
11 import com.shore.dao.IUserDao;
12 import com.shore.entity.Department;
13 import com.shore.entity.Role;
14 import com.shore.entity.User;
15 
16 /**
17  * @author DSHORE/2020-3-27
18  *
19  */
20 public class UserDaoTest {
21     ApplicationContext context = new ClassPathXmlApplicationContext("conf/beans.xml");
22     IUserDao userDao = (IUserDao) context.getBean("userDao");
23     IRoleDao roleDao = (IRoleDao) context.getBean("roleDao");
24     IDepartmentDao departmentDao = (IDepartmentDao) context.getBean("departmentDao");
25     
26     @Test //根据账号查询
27     public void testFindByAccount() {
28         System.out.println(userDao.findByAccount("lisi"));
29         /* 返回值:
30          * User [id=2, name=李四, sex=0, account=lisi, password=123456, email=12345678, telphone=12345678@qq.com, flag=0, department=null, roles=[]]
31          * 这里只需要查询该账号是否存在,后面的department=null, roles=[],没有值,不再做处理,为空也没关系。
32          * */
33     }
34     
35     @Test //查询所有用户(含关联表的数据)
36     public void testListAllUser() {
37         List<User> users = userDao.listAll();
38         for (User user : users) {
39             System.out.println(user);
40             /* 返回值:
41              * User [id=2, name=李四, sex=0, account=lisi, password=123456, email=12345678, telphone=12345678@qq.com, flag=0, department=Department [id=3, name=软件开发部, description=软件开发, users=null], roles=[Role [id=3, name=普通管理员, privilege_id=1, users=null], Role [id=2, name=财务部管理员, privilege_id=3, users=null], Role [id=1, name=超级管理员, privilege_id=2, users=null]]]
42              * User [id=3, name=王五, sex=1, account=wangwu, password=123456, email=12345678, telphone=12345678@qq.com, flag=1, department=Department [id=2, name=财务部, description=财务, users=null], roles=[Role [id=3, name=普通管理员, privilege_id=1, users=null], Role [id=2, name=财务部管理员, privilege_id=3, users=null], Role [id=1, name=超级管理员, privilege_id=2, users=null]]]
43              * User [id=4, name=赵六, sex=1, account=zhaoliu, password=123456, email=12345678, telphone=12345678@qq.com, flag=1, department=Department [id=3, name=软件开发部, description=软件开发, users=null], roles=[Role [id=3, name=普通管理员, privilege_id=1, users=null], Role [id=2, name=财务部管理员, privilege_id=3, users=null], Role [id=1, name=超级管理员, privilege_id=2, users=null]]]
44              * */
45         }
46         System.out.println(userDao.listAll().get(0).getDepartment().getName());//返回值:人事部
47         System.out.println(userDao.listAll().get(0).getRoles().get(0).getName());//返回值:普通管理员
48         
49     }
50     
51     @Test //查询所有角色
52     public void testListAllRole() {
53         List<Role> roles = roleDao.listAll();
54         for (Role role : roles) {
55             System.out.println(role);
56             /* 返回值:
57              * Role [id=1, name=超级管理员, privilege_id=2, users=[User [id=1, name=超级管理员, sex=null, account=null, password=null, email=null, telphone=null, flag=null, department=null, roles=null]]]
58              * Role [id=2, name=财务部管理员, privilege_id=3, users=[User [id=2, name=财务部管理员, sex=null, account=null, password=null, email=null, telphone=null, flag=null, department=null, roles=null]]]
59              * Role [id=3, name=普通管理员, privilege_id=1, users=[User [id=3, name=普通管理员, sex=null, account=null, password=null, email=null, telphone=null, flag=null, department=null, roles=null]]]
60              * 
61              * 1、后面users中的id和name都和Role表中的一模一样,是应为他们同名了,到对应的xxxMapper.xml中,对应的sql语句中取个别名即可解决此问题。
62              * 2、users的中值为空,不再做处理,处理方法:看testListAllUser()方法的处理流程
63              * */
64         }
65     }
66     
67     @Test //查询所有角色
68     public void testListAllDepartment() {
69         List<Department> departments = departmentDao.listAll();
70         for (Department department : departments) {
71             System.out.println(department);
72             /* 返回值:
73              * Department [id=1, name=人事部, description=hr, users=[User [id=1, name=人事部, sex=null, account=null, password=null, email=null, telphone=null, flag=null, department=null, roles=null]]]
74              * Department [id=2, name=财务部, description=财务, users=[User [id=2, name=财务部, sex=null, account=null, password=null, email=null, telphone=null, flag=null, department=null, roles=null]]]
75              * Department [id=3, name=软件开发部, description=软件开发, users=[User [id=3, name=软件开发部, sex=null, account=null, password=null, email=null, telphone=null, flag=null, department=null, roles=null]]]
76              *
77              * 1、后面users中的id和name都和Department表中的一模一样,是应为他们同名了,到对应的xxxMapper.xml中,对应的sql语句中取个别名即可解决此问题。
78              * 2、users的中值为空,不再做处理,处理方法:看testListAllUser()方法的处理流程
79              * */
80         }
81     }
82 }

 

 

 

 

 

 

 

原创作者:DSHORE

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

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

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

posted @ 2020-03-22 21:25  DSHORE  阅读(497)  评论(0编辑  收藏  举报