【shiro】2.spring整合shiro,注解控制shiro用户/角色/权限And/OR,没有权限跳转到固定页面

这几天粗浅的把shiro整合到spring中,并且注解控制shiro用户/角色/权限And/OR

步骤:

1.首先maven搭建web项目

【shiro】2.spring整合shiro,注解控制shiro用户/角色/权限And/OR,没有权限跳转到固定页面

2.创建数据库 user/role/authority 其中,role->user是一对多,role->authority是多对多

【shiro】2.spring整合shiro,注解控制shiro用户/角色/权限And/OR,没有权限跳转到固定页面

shiros.sql内容:

【shiro】2.spring整合shiro,注解控制shiro用户/角色/权限And/OR,没有权限跳转到固定页面【shiro】2.spring整合shiro,注解控制shiro用户/角色/权限And/OR,没有权限跳转到固定页面
 1 /*
 2 SQLyog Ultimate v11.24 (32 bit)
 3 MySQL - 5.5.41 : Database - shiros
 4 *********************************************************************
 5 */
 6 
 7 
 8 /*!40101 SET NAMES utf8 */;
 9 
10 /*!40101 SET SQL_MODE=''*/;
11 
12 /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
13 /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
14 /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
15 /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
16 CREATE DATABASE /*!32312 IF NOT EXISTS*/`shiros` /*!40100 DEFAULT CHARACTER SET utf8 */;
17 
18 USE `shiros`;
19 
20 /*Table structure for table `authority` */
21 
22 DROP TABLE IF EXISTS `authority`;
23 
24 CREATE TABLE `authority` (
25   `authorityId` varchar(36) NOT NULL,
26   `authorityName` varchar(20) DEFAULT NULL,
27   `authorityContent` varchar(500) DEFAULT NULL,
28   PRIMARY KEY (`authorityId`)
29 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
30 
31 /*Data for the table `authority` */
32 
33 insert  into `authority`(`authorityId`,`authorityName`,`authorityContent`) values ('97e2a86d-802c-415f-8d2e-6d94a3390001','疾病:增加',NULL),('97e2a86d-802c-415f-8d2e-6d94a3390002','疾病:删除',NULL),('97e2a86d-802c-415f-8d2e-6d94a3390003','疾病:修改',NULL),('97e2a86d-802c-415f-8d2e-6d94a3390004','疾病:查看',NULL),('97e2a86d-802c-415f-8d2e-6d94a3390005','产品:增加',NULL),('97e2a86d-802c-415f-8d2e-6d94a3390006','产品:删除',NULL),('97e2a86d-802c-415f-8d2e-6d94a3390007','产品:修改',NULL),('97e2a86d-802c-415f-8d2e-6d94a3390008','产品:查看',NULL);
34 
35 /*Table structure for table `role` */
36 
37 DROP TABLE IF EXISTS `role`;
38 
39 CREATE TABLE `role` (
40   `roleId` varchar(36) NOT NULL,
41   `roleName` varchar(36) DEFAULT NULL,
42   `roleGrade` int(11) DEFAULT NULL,
43   PRIMARY KEY (`roleId`)
44 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
45 
46 /*Data for the table `role` */
47 
48 insert  into `role`(`roleId`,`roleName`,`roleGrade`) values ('97e2a86d-802c-415f-8d2e-6d94a3390121','管理员3',1),('97e2a86d-802c-415f-8d2e-6d94a3390122','管理员2',1),('97e2a86d-802c-415f-8d2e-6d94a3390123','管理员1',1);
49 
50 /*Table structure for table `roleauthority` */
51 
52 DROP TABLE IF EXISTS `roleauthority`;
53 
54 CREATE TABLE `roleauthority` (
55   `roleId` varchar(36) NOT NULL,
56   `authorityId` varchar(36) NOT NULL,
57   PRIMARY KEY (`roleId`,`authorityId`),
58   KEY `FK_Relationship_3` (`authorityId`),
59   CONSTRAINT `FK_Relationship_2` FOREIGN KEY (`roleId`) REFERENCES `role` (`roleId`),
60   CONSTRAINT `FK_Relationship_3` FOREIGN KEY (`authorityId`) REFERENCES `authority` (`authorityId`)
61 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
62 
63 /*Data for the table `roleauthority` */
64 
65 insert  into `roleauthority`(`roleId`,`authorityId`) values ('97e2a86d-802c-415f-8d2e-6d94a3390123','97e2a86d-802c-415f-8d2e-6d94a3390001'),('97e2a86d-802c-415f-8d2e-6d94a3390123','97e2a86d-802c-415f-8d2e-6d94a3390002'),('97e2a86d-802c-415f-8d2e-6d94a3390123','97e2a86d-802c-415f-8d2e-6d94a3390003'),('97e2a86d-802c-415f-8d2e-6d94a3390123','97e2a86d-802c-415f-8d2e-6d94a3390004'),('97e2a86d-802c-415f-8d2e-6d94a3390122','97e2a86d-802c-415f-8d2e-6d94a3390005'),('97e2a86d-802c-415f-8d2e-6d94a3390122','97e2a86d-802c-415f-8d2e-6d94a3390006');
66 
67 /*Table structure for table `user` */
68 
69 DROP TABLE IF EXISTS `user`;
70 
71 CREATE TABLE `user` (
72   `userId` varchar(36) NOT NULL,
73   `roleId` varchar(36) NOT NULL,
74   `userName` varchar(20) DEFAULT NULL,
75   `password` varchar(20) DEFAULT NULL,
76   PRIMARY KEY (`userId`),
77   KEY `FK_Relationship_1` (`roleId`),
78   CONSTRAINT `FK_Relationship_1` FOREIGN KEY (`roleId`) REFERENCES `role` (`roleId`)
79 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
80 
81 /*Data for the table `user` */
82 
83 insert  into `user`(`userId`,`roleId`,`userName`,`password`) values ('97e2a86d-802c-415f-8d2e-6d94a3390110','97e2a86d-802c-415f-8d2e-6d94a3390122','李四','123456'),('97e2a86d-802c-415f-8d2e-6d94a3390111','97e2a86d-802c-415f-8d2e-6d94a3390123','张三','123456'),('97e2a86d-802c-415f-8d2e-6d94a3390112','97e2a86d-802c-415f-8d2e-6d94a3390121','王五','123456');
84 
85 /*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
86 /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
87 /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
88 /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
View Code

3.创建完成之后,使用hibernate反转工具,生成实体

【shiro】2.spring整合shiro,注解控制shiro用户/角色/权限And/OR,没有权限跳转到固定页面

user.java

【shiro】2.spring整合shiro,注解控制shiro用户/角色/权限And/OR,没有权限跳转到固定页面【shiro】2.spring整合shiro,注解控制shiro用户/角色/权限And/OR,没有权限跳转到固定页面
 1 package com.sxd.entity;
 2 
 3 import javax.persistence.Column;
 4 import javax.persistence.Entity;
 5 import javax.persistence.FetchType;
 6 import javax.persistence.GeneratedValue;
 7 import javax.persistence.Id;
 8 import javax.persistence.JoinColumn;
 9 import javax.persistence.ManyToOne;
10 import javax.persistence.Table;
11 import org.hibernate.annotations.GenericGenerator;
12 
13 /**
14  * User entity. @author MyEclipse Persistence Tools
15  */
16 @Entity
17 @Table(name = "user", catalog = "shiros")
18 public class User implements java.io.Serializable {
19 
20     // Fields
21 
22     private String userId;
23     private Role role;
24     private String userName;
25     private String password;
26 
27     // Constructors
28 
29     /** default constructor */
30     public User() {
31     }
32 
33     /** minimal constructor */
34     public User(Role role) {
35         this.role = role;
36     }
37 
38     /** full constructor */
39     public User(Role role, String userName, String password) {
40         this.role = role;
41         this.userName = userName;
42         this.password = password;
43     }
44 
45     // Property accessors
46     @GenericGenerator(name = "generator", strategy = "uuid.hex")
47     @Id
48     @GeneratedValue(generator = "generator")
49     @Column(name = "userId", unique = true, nullable = false, length = 36)
50     public String getUserId() {
51         return this.userId;
52     }
53 
54     public void setUserId(String userId) {
55         this.userId = userId;
56     }
57 
58     @ManyToOne(fetch = FetchType.LAZY)
59     @JoinColumn(name = "roleId", nullable = false)
60     public Role getRole() {
61         return this.role;
62     }
63 
64     public void setRole(Role role) {
65         this.role = role;
66     }
67 
68     @Column(name = "userName", length = 20)
69     public String getUserName() {
70         return this.userName;
71     }
72 
73     public void setUserName(String userName) {
74         this.userName = userName;
75     }
76 
77     @Column(name = "password", length = 20)
78     public String getPassword() {
79         return this.password;
80     }
81 
82     public void setPassword(String password) {
83         this.password = password;
84     }
85 
86 }
View Code

role.java

【shiro】2.spring整合shiro,注解控制shiro用户/角色/权限And/OR,没有权限跳转到固定页面【shiro】2.spring整合shiro,注解控制shiro用户/角色/权限And/OR,没有权限跳转到固定页面
 1 package com.sxd.entity;
 2 
 3 import java.util.HashSet;
 4 import java.util.Set;
 5 import javax.persistence.CascadeType;
 6 import javax.persistence.Column;
 7 import javax.persistence.Entity;
 8 import javax.persistence.FetchType;
 9 import javax.persistence.GeneratedValue;
10 import javax.persistence.Id;
11 import javax.persistence.JoinColumn;
12 import javax.persistence.JoinTable;
13 import javax.persistence.ManyToMany;
14 import javax.persistence.OneToMany;
15 import javax.persistence.Table;
16 import org.hibernate.annotations.GenericGenerator;
17 
18 /**
19  * Role entity. @author MyEclipse Persistence Tools
20  */
21 @Entity
22 @Table(name = "role", catalog = "shiros")
23 public class Role implements java.io.Serializable {
24 
25     // Fields
26 
27     private String roleId;
28     private String roleName;
29     private Integer roleGrade;
30     private Set<Authority> authorities = new HashSet<Authority>(0);
31     private Set<User> users = new HashSet<User>(0);
32 
33     // Constructors
34 
35     /** default constructor */
36     public Role() {
37     }
38 
39     /** full constructor */
40     public Role(String roleName, Integer roleGrade, Set<Authority> authorities,
41             Set<User> users) {
42         this.roleName = roleName;
43         this.roleGrade = roleGrade;
44         this.authorities = authorities;
45         this.users = users;
46     }
47 
48     // Property accessors
49     @GenericGenerator(name = "generator", strategy = "uuid.hex")
50     @Id
51     @GeneratedValue(generator = "generator")
52     @Column(name = "roleId", unique = true, nullable = false, length = 36)
53     public String getRoleId() {
54         return this.roleId;
55     }
56 
57     public void setRoleId(String roleId) {
58         this.roleId = roleId;
59     }
60 
61     @Column(name = "roleName", length = 36)
62     public String getRoleName() {
63         return this.roleName;
64     }
65 
66     public void setRoleName(String roleName) {
67         this.roleName = roleName;
68     }
69 
70     @Column(name = "roleGrade")
71     public Integer getRoleGrade() {
72         return this.roleGrade;
73     }
74 
75     public void setRoleGrade(Integer roleGrade) {
76         this.roleGrade = roleGrade;
77     }
78 
79     @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
80     @JoinTable(name = "roleauthority", catalog = "shiros", joinColumns = { @JoinColumn(name = "roleId", nullable = false, updatable = false) }, inverseJoinColumns = { @JoinColumn(name = "authorityId", nullable = false, updatable = false) })
81     public Set<Authority> getAuthorities() {
82         return this.authorities;
83     }
84 
85     public void setAuthorities(Set<Authority> authorities) {
86         this.authorities = authorities;
87     }
88 
89     @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "role")
90     public Set<User> getUsers() {
91         return this.users;
92     }
93 
94     public void setUsers(Set<User> users) {
95         this.users = users;
96     }
97 
98 }
View Code

Authority.java

【shiro】2.spring整合shiro,注解控制shiro用户/角色/权限And/OR,没有权限跳转到固定页面【shiro】2.spring整合shiro,注解控制shiro用户/角色/权限And/OR,没有权限跳转到固定页面
 1 package com.sxd.entity;
 2 
 3 import java.util.HashSet;
 4 import java.util.Set;
 5 import javax.persistence.CascadeType;
 6 import javax.persistence.Column;
 7 import javax.persistence.Entity;
 8 import javax.persistence.FetchType;
 9 import javax.persistence.GeneratedValue;
10 import javax.persistence.Id;
11 import javax.persistence.ManyToMany;
12 import javax.persistence.Table;
13 import org.hibernate.annotations.GenericGenerator;
14 
15 /**
16  * Authority entity. @author MyEclipse Persistence Tools
17  */
18 @Entity
19 @Table(name = "authority", catalog = "shiros")
20 public class Authority implements java.io.Serializable {
21 
22     // Fields
23 
24     private String authorityId;
25     private String authorityName;
26     private String authorityContent;
27     private Set<Role> roles = new HashSet<Role>(0);
28 
29     // Constructors
30 
31     /** default constructor */
32     public Authority() {
33     }
34 
35     /** full constructor */
36     public Authority(String authorityName, String authorityContent,
37             Set<Role> roles) {
38         this.authorityName = authorityName;
39         this.authorityContent = authorityContent;
40         this.roles = roles;
41     }
42 
43     // Property accessors
44     @GenericGenerator(name = "generator", strategy = "uuid.hex")
45     @Id
46     @GeneratedValue(generator = "generator")
47     @Column(name = "authorityId", unique = true, nullable = false, length = 36)
48     public String getAuthorityId() {
49         return this.authorityId;
50     }
51 
52     public void setAuthorityId(String authorityId) {
53         this.authorityId = authorityId;
54     }
55 
56     @Column(name = "authorityName", length = 20)
57     public String getAuthorityName() {
58         return this.authorityName;
59     }
60 
61     public void setAuthorityName(String authorityName) {
62         this.authorityName = authorityName;
63     }
64 
65     @Column(name = "authorityContent", length = 500)
66     public String getAuthorityContent() {
67         return this.authorityContent;
68     }
69 
70     public void setAuthorityContent(String authorityContent) {
71         this.authorityContent = authorityContent;
72     }
73 
74     @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "authorities")
75     public Set<Role> getRoles() {
76         return this.roles;
77     }
78 
79     public void setRoles(Set<Role> roles) {
80         this.roles = roles;
81     }
82 
83 }
View Code

4.接下来,pom.xml文件配置

【shiro】2.spring整合shiro,注解控制shiro用户/角色/权限And/OR,没有权限跳转到固定页面【shiro】2.spring整合shiro,注解控制shiro用户/角色/权限And/OR,没有权限跳转到固定页面
  1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  2   <modelVersion>4.0.0</modelVersion>
  3   <groupId>com.sxd.shiro</groupId>
  4   <artifactId>shiro-first</artifactId>
  5   <version>0.0.1-SNAPSHOT</version>
  6   <packaging>war</packaging>
  7   <build>
  8       <plugins>
  9           <plugin>
 10               <artifactId>maven-war-plugin</artifactId>
 11               <configuration>
 12                   <version>3.0</version>
 13               </configuration>
 14           </plugin>
 15       </plugins>
 16   </build>
 17   
 18   <properties>
 19       <shiro.version>1.3.2</shiro.version>
 20       <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 21       <spring.version>4.1.4.RELEASE</spring.version>
 22       <hibernate.version>4.3.8.Final</hibernate.version>
 23   </properties>
 24   
 25   <dependencies>
 26       <!-- Logging API + implementation: -->
 27       <dependency>
 28           <groupId>org.slf4j</groupId>
 29           <artifactId>slf4j-api</artifactId>
 30           <version>1.7.21</version>
 31       </dependency>
 32       <dependency>
 33           <groupId>org.slf4j</groupId>
 34           <artifactId>jcl-over-slf4j</artifactId>
 35           <version>1.7.21</version>
 36           <scope>runtime</scope>
 37       </dependency>
 38       
 39        <!-- Shiro dependencies: -->
 40        <dependency>
 41            <groupId>org.apache.shiro</groupId>
 42            <artifactId>shiro-core</artifactId>
 43            <version>${shiro.version}</version>
 44        </dependency>
 45        <dependency>
 46            <groupId>org.apache.shiro</groupId>
 47            <artifactId>shiro-web</artifactId>
 48            <version>${shiro.version}</version>
 49        </dependency>
 50        <dependency>
 51             <groupId>org.apache.shiro</groupId>
 52             <artifactId>shiro-spring</artifactId>
 53             <version>${shiro.version}</version>
 54         </dependency>
 55        
 56     <!-- https://mvnrepository.com/artifact/javax.persistence/persistence-api -->
 57     <dependency>
 58         <groupId>javax.persistence</groupId>
 59         <artifactId>persistence-api</artifactId>
 60         <version>1.0</version>
 61     </dependency>
 62       <!-- 进行加密操作 -->
 63         <dependency>
 64             <groupId>commons-codec</groupId>
 65             <artifactId>commons-codec</artifactId>
 66             <version>1.10</version>
 67         </dependency>
 68           
 69           <!-- https://mvnrepository.com/artifact/dom4j/dom4j -->
 70         <dependency>
 71             <groupId>dom4j</groupId>
 72             <artifactId>dom4j</artifactId>
 73             <version>1.6.1</version>
 74         </dependency>
 75 
 76           
 77       <!-- 微信开发工具包 -->
 78         
 79         <!-- https://mvnrepository.com/artifact/com.github.binarywang/weixin-java-common -->
 80         <dependency>
 81             <groupId>com.github.binarywang</groupId>
 82             <artifactId>weixin-java-common</artifactId>
 83             <version>2.2.0</version>
 84         </dependency>
 85         <!-- https://mvnrepository.com/artifact/com.github.binarywang/weixin-java-mp -->
 86         <dependency>
 87             <groupId>com.github.binarywang</groupId>
 88             <artifactId>weixin-java-mp</artifactId>
 89             <version>2.2.0</version>
 90         </dependency>
 91         
 92         
 93         <!-- junit -->
 94         <dependency>
 95             <groupId>junit</groupId>
 96             <artifactId>junit</artifactId>
 97             <version>4.12</version>
 98             <scope>test</scope>
 99         </dependency>
100 
101         <!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper -->
102         <dependency>
103             <groupId>com.github.pagehelper</groupId>
104             <artifactId>pagehelper</artifactId>
105             <version>4.1.4</version>
106         </dependency>
107         
108         <!-- spring -->
109         <dependency>
110             <groupId>org.springframework</groupId>
111             <artifactId>spring-core</artifactId>
112             <version>${spring.version}</version>
113         </dependency>
114 
115         <dependency>
116             <groupId>org.springframework</groupId>
117             <artifactId>spring-beans</artifactId>
118             <version>${spring.version}</version>
119         </dependency>
120 
121         <dependency>
122             <groupId>org.springframework</groupId>
123             <artifactId>spring-context</artifactId>
124             <version>${spring.version}</version>
125         </dependency>
126 
127         <dependency>
128             <groupId>org.springframework</groupId>
129             <artifactId>spring-tx</artifactId>
130             <version>${spring.version}</version>
131         </dependency>
132 
133         <dependency>
134             <groupId>org.springframework</groupId>
135             <artifactId>spring-web</artifactId>
136             <version>${spring.version}</version>
137         </dependency>
138 
139         <dependency>
140             <groupId>org.springframework</groupId>
141             <artifactId>spring-test</artifactId>
142             <version>${spring.version}</version>
143             <scope>test</scope>
144         </dependency>
145 
146         <!-- 使用SpringMVC需配置 -->
147         <dependency>
148             <groupId>org.springframework</groupId>
149             <artifactId>spring-webmvc</artifactId>
150             <version>${spring.version}</version>
151         </dependency>
152         <!-- spring cglib 代理 -->
153         <dependency>
154             <groupId>cglib</groupId>
155             <artifactId>cglib</artifactId>
156             <version>2.2.2</version>
157         </dependency>
158         <!-- 关系型数据库整合时需配置 如hibernate jpa等 -->
159         <dependency>
160             <groupId>org.springframework</groupId>
161             <artifactId>spring-orm</artifactId>
162             <version>${spring.version}</version>
163         </dependency>
164 
165         <!-- hibernate -->
166         <dependency>
167             <groupId>org.hibernate</groupId>
168             <artifactId>hibernate-core</artifactId>
169             <version>${hibernate.version}</version>
170             
171         </dependency>
172 
173         <dependency>
174             <groupId>org.hibernate</groupId>
175             <artifactId>hibernate-ehcache</artifactId>
176             <version>${hibernate.version}</version>
177         </dependency>
178 
179         <!-- 二级缓存ehcache -->
180         <dependency>
181             <groupId>net.sf.ehcache</groupId>
182             <artifactId>ehcache</artifactId>
183             <version>2.9.0</version>
184         </dependency>
185 
186         <!-- log4j -->
187         <dependency>
188             <groupId>log4j</groupId>
189             <artifactId>log4j</artifactId>
190             <version>1.2.17</version>
191         </dependency>
192 
193         <!-- mysql连接 -->
194         <dependency>
195             <groupId>mysql</groupId>
196             <artifactId>mysql-connector-java</artifactId>
197             <version>5.1.34</version>
198         </dependency>
199 
200         <!-- c3p0数据源 -->
201         <dependency>
202             <groupId>com.mchange</groupId>
203             <artifactId>c3p0</artifactId>
204             <version>0.9.5-pre10</version>
205         </dependency>
206 
207         <!-- json -->
208 
209         <!-- 1号 -->
210         <dependency>
211             <groupId>com.fasterxml.jackson.core</groupId>
212             <artifactId>jackson-core</artifactId>
213             <version>2.8.1</version>
214         </dependency>
215         <!-- 2号 -->
216         <dependency>
217             <groupId>com.fasterxml.jackson.core</groupId>
218             <artifactId>jackson-annotations</artifactId>
219             <version>2.8.1</version>
220         </dependency>
221 
222         <!-- 3号 -->
223         <dependency>
224             <groupId>com.fasterxml.jackson.core</groupId>
225             <artifactId>jackson-databind</artifactId>
226             <version>2.8.1</version>
227             <exclusions>
228                 <exclusion>
229                     <artifactId>jackson-core</artifactId>
230                     <groupId>com.fasterxml.jackson.core</groupId>
231                 </exclusion>
232                 <exclusion>
233                     <artifactId>jackson-annotations</artifactId>
234                     <groupId>com.fasterxml.jackson.core</groupId>
235                 </exclusion>
236             </exclusions>
237         </dependency>
238 
239         <!-- 4号 -->
240         <dependency>
241             <groupId>com.google.code.gson</groupId>
242             <artifactId>gson</artifactId>
243             <version>2.7</version>
244         </dependency>
245         <!-- 5号 -->
246         <dependency>
247             <groupId>net.sf.json-lib</groupId>
248             <artifactId>json-lib</artifactId>
249             <version>2.4</version>
250             <classifier>jdk15</classifier>
251         </dependency>
252         <!-- 5号json-lib还需要以下依赖包 -->
253         <dependency>
254             <groupId>commons-lang</groupId>
255             <artifactId>commons-lang</artifactId>
256             <version>2.5</version>
257         </dependency>
258         <dependency>
259             <groupId>commons-beanutils</groupId>
260             <artifactId>commons-beanutils</artifactId>
261             <version>1.9.2</version>
262         </dependency>
263         <dependency>
264             <groupId>commons-collections</groupId>
265             <artifactId>commons-collections</artifactId>
266             <version>3.2.1</version>
267         </dependency>
268         <dependency>
269             <groupId>commons-logging</groupId>
270             <artifactId>commons-logging</artifactId>
271             <version>1.2</version>
272         </dependency>
273         
274         <!-- aop -->
275         <dependency>
276             <groupId>org.aspectj</groupId>
277             <artifactId>aspectjweaver</artifactId>
278             <version>1.8.4</version>
279         </dependency>
280 
281         <!-- servlet -->
282         <dependency>
283             <groupId>javax.servlet</groupId>
284             <artifactId>servlet-api</artifactId>
285             <version>3.0-alpha-1</version>
286             <scope>provided</scope>
287         </dependency>
288 
289         <dependency>
290             <groupId>javax.servlet</groupId>
291             <artifactId>jstl</artifactId>
292             <version>1.2</version>
293         </dependency>
294         <!-- guava 集合的交并操作 -->        
295         <dependency>
296             <groupId>com.google.guava</groupId>
297             <artifactId>guava</artifactId>
298             <version>19.0</version>
299         </dependency>
300         <dependency>
301             <groupId>com.google.guava</groupId>
302             <artifactId>guava-collections</artifactId>
303             <version>r03</version>
304         </dependency>
305         
306         <!-- 文件上传 -->
307         <dependency>
308             <groupId>commons-fileupload</groupId>
309             <artifactId>commons-fileupload</artifactId>
310             <version>1.3.1</version>
311         </dependency>
312         
313   </dependencies>
314   
315 </project>
View Code

尤其注意,这里着重看一下shiro的架包就是下面三个:版本号自行选择

 1 <!-- Shiro dependencies: -->
 2        <dependency>
 3            <groupId>org.apache.shiro</groupId>
 4            <artifactId>shiro-core</artifactId>
 5            <version>${shiro.version}</version>
 6        </dependency>
 7        <dependency>
 8            <groupId>org.apache.shiro</groupId>
 9            <artifactId>shiro-web</artifactId>
10            <version>${shiro.version}</version>
11        </dependency>
12        <dependency>
13             <groupId>org.apache.shiro</groupId>
14             <artifactId>shiro-spring</artifactId>
15             <version>${shiro.version}</version>
16         </dependency>

5.为实体生成对应的Dao/service以及其impl

【shiro】2.spring整合shiro,注解控制shiro用户/角色/权限And/OR,没有权限跳转到固定页面

 

GenericDao.java

【shiro】2.spring整合shiro,注解控制shiro用户/角色/权限And/OR,没有权限跳转到固定页面【shiro】2.spring整合shiro,注解控制shiro用户/角色/权限And/OR,没有权限跳转到固定页面
  1 package com.sxd.dao;
  2 
  3 import java.io.Serializable;
  4 import java.util.Collection;
  5 import java.util.List;
  6 import java.util.Map;
  7 
  8 import org.hibernate.Criteria;
  9 import org.hibernate.criterion.Criterion;
 10 import org.hibernate.criterion.DetachedCriteria;
 11 
 12 import com.github.pagehelper.PageInfo;
 13 
 14 
 15 public interface GenericDao<T, PK extends Serializable> {
 16     /**
 17      * 查询全部,可以排序
 18      * @param orderBy
 19      * @param isAsc
 20      * @return List<T>
 21      */
 22     public List<T> list(Criteria criteria);
 23 
 24     /**
 25      * 查询全部,可以排序
 26      * @param orderBy
 27      * @param isAsc
 28      * @return List<T>
 29      */
 30     public List<T> list(String orderBy, boolean isAsc);
 31     
 32     /**
 33      * 离线查询
 34      * @param criteria
 35      * @return List<T>
 36      */
 37     public List<T> list(DetachedCriteria criteria);
 38     
 39     /**
 40      * 根据Criteria查询条件,获取总数
 41      * @param criteria
 42      * @return int
 43      * @throws SecurityException 
 44      * @throws NoSuchFieldException 
 45      * @throws IllegalAccessException 
 46      * @throws IllegalArgumentException 
 47      */
 48     public int countAll(Criteria criteria);
 49     
 50     /**
 51      * 获取总数(默认为entityClass) 即查询总条数
 52      * @return int
 53      */
 54     public int countAll();
 55     
 56     /**
 57      * 根据I判断是否存在
 58      * @param id
 59      * @return boolean
 60      */
 61     public boolean exists(PK id);
 62     
 63     /**
 64      * 保存实体 
 65      * @param t 实体参数
 66      */
 67     public void save(T t);
 68 
 69     /**
 70      * 保存或者更新实体
 71      * @param t 实体
 72      */
 73     public void saveOrUpdate(T t);
 74 
 75     /**
 76      * 加载实体的通过load方法
 77      * @param id 实体的id
 78      * @return 查询出来的实体
 79      */
 80     public T load(PK id);
 81     
 82     /**
 83      * 合并实体 
 84      * @param entity
 85      */
 86     public void merge(T entity);
 87     
 88     /**
 89      * 查找全部
 90      */
 91     public List<T> findAll();
 92 
 93     /**
 94      * 通过get方法加载实体的
 95      * @param id 实体的id
 96      * @return 查询出来的实体
 97      */
 98     public T get(PK id);
 99 
100     /**
101      * contains
102      * @param t 实体
103      * @return 是否包含
104      */
105     public boolean contains(T t);
106 
107     /**
108      * delete
109      * @param t
110      * 删除实体
111      */
112     public void delete(T t);
113 
114     /**
115      * 根据ID删除数据
116      * @param Id 实体id
117      * @return 是否删除成功
118      */
119     public boolean deleteById(PK Id);
120 
121     /**
122      * 删除所有
123      * @param entities 实体的Collection集合
124      */
125     public void deleteAll(Collection<T> entities);
126 
127     /**
128      * 执行Hql语句 要求 hql中参数顺序与可变参数 中参数顺序相一致
129      * @param hqlString hql
130      * @param values 不定参数数组
131      */
132     public void queryHql(String hqlString, Object... values);
133 
134     /**
135      * 执行Sql语句(不建议用,影响扩展)
136      * @param sqlString sql
137      * @param values 不定参数数组
138      */
139     public void querySql(String sqlString, Object... values);
140 
141     /**
142      * 根据HQL语句查找唯一实体
143      * 
144      * @param hqlString HQL语句
145      * @param values 不定参数的Object数组
146      * @return 查询实体
147      */
148     public T getByHQL(String hqlString, Object... values);
149     
150     /**
151      * 根据SQL语句查找唯一实体(不建议用,影响扩展)
152      * @param sqlString SQL语句
153      * @param values 不定参数的Object数组
154      * @return 查询实体
155      */
156 
157     /**
158      * 根据HQL语句,得到对应的list
159      * @param hqlString HQL语句
160      * @param values 不定参数的Object数组
161      * @return 查询多个实体的List集合
162      */
163     public List<T> getListByHQL(String hqlString, Object... values);
164 
165     /**
166      * 根据SQL语句,得到对应的list(不建议用,影响扩展)
167      * @param sqlString HQL语句
168      * @param values 不定参数的Object数组
169      * @return 查询多个实体的List集合
170      */
171     public List<T> getListBySQL(String sqlString,Class c, Object... values);
172 
173     /**
174      * refresh 刷新实体,强制与数据库两步 refresh方法应该是数据库的数据更新到本地的person实体中,而不是本地person更新数据到数据库中  也就是执行refresh方法是更新了java代码中变量的数据值
175      * @param t 实体
176      */
177     public void refresh(T t);
178 
179     /**
180      * update
181      * @param t
182      * 更新的是数据库中的数据
183      */
184     public void update(T t);
185 
186     /**
187      * 根据HQL得到记录数
188      * @param hql HQL语句
189      * @param values 不定参数的Object数组
190      * @return 记录总数
191      */
192     public Long countByHql(String hql, Object... values);
193 
194     /**
195      * HQL分页查询
196      * 
197      * @param hql HQL语句
198      * @param countHql 查询记录条数的HQL语句
199      * @param pageNo 下一页
200      * @param pageSize 一页总条数
201      * @param values  不定Object数组参数
202      * @return PageResults的封装类,里面包含了页码的信息以及查询的数据List集合
203      */
204     public  PageInfo<T> findPageByHql(String hql, String countHql, int pageNo, int pageSize, Object... values);
205     
206     /**
207      * 按属性查找对象列表,匹配方式为相等
208      * @param propertyName
209      * @param value
210      * @return List<T>
211      */
212     public List<T> list(String propertyName, Object value);
213     
214     /**
215      * 根据criterion查询条件获取数据列表
216      * @param criterion
217      * @return List<T>
218      */
219     public List<T> list(Criterion criterion);
220     
221     /**
222      * 按Criteria查询对象列表
223      * @param criterions
224      * @return List<T>
225      */
226     public List<T> list(Criterion... criterions);
227     
228     /**
229      * 按属性查找唯一对象,匹配方式为相等
230      * @param propertyName
231      * @param value
232      * @return T
233      */
234     public T uniqueResult(String propertyName, Object value);
235     
236     /**
237      * 按Criteria查询唯一对象
238      * @param criterions
239      * @return T
240      */
241     public T uniqueResult(Criterion... criterions);
242     
243     /**
244      * 按Criteria查询唯一对象
245      * @param criteria
246      * @return T
247      */
248     public T uniqueResult(Criteria criteria);
249     
250     /**
251      * 按criteria查询某个Integer类型的字段
252      * @param criteria
253      * @return
254      */
255     public Integer uniqueResultInt(Criteria criteria);
256     
257     /**
258      * 为Criteria添加distinct transformer
259      * @param criteria
260      * @return Criteria
261      */
262     public Criteria distinct(Criteria criteria);
263     
264     /**
265      * 刷新session
266      */
267     public void flush();
268     
269     /**
270      * 清空session
271      */
272     public void clear();
273     
274     /**
275      * 创建Criteria实例
276      */
277     public Criteria createCriteria();
278     
279     /**
280      * 根据Criterion条件创建Criteria
281      * @param criterions
282      * @return Criteria
283      */
284     public Criteria createCriteria(Criterion... criterions);
285     
286     /**
287      * 分页查询Criteria
288      * @param criteria 
289      * @param pageNo 下页页码
290      * @param pageSize 页面数据量
291      * @return List<T>
292      */
293     public List<T> findPage(Criteria criteria, int pageNo, int pageSize);
294     
295     /**
296      * 分页查询Criteria
297      * @param criteria
298      * @param pageNo
299      * @param pageSize
300      * @return PageInfo<T>
301      * @throws SecurityException 
302      * @throws NoSuchFieldException 
303      * @throws IllegalAccessException 
304      * @throws IllegalArgumentException 
305      */
306     public PageInfo<T> findQuery(Criteria criteria, int pageNo, int pageSize);
307     
308     /**
309      * 
310      * @param hql
311      * @param pageNo
312      * @param pageSize
313      * @param map
314      * @return List<T>
315      */
316     public List<T> findQuery(String hql, int pageNo, int pageSize, Map<?, ?> map);
317 
318 }
View Code

GenericDaoImpl.java

【shiro】2.spring整合shiro,注解控制shiro用户/角色/权限And/OR,没有权限跳转到固定页面【shiro】2.spring整合shiro,注解控制shiro用户/角色/权限And/OR,没有权限跳转到固定页面
  1 package com.sxd.dao.impl;
  2 
  3 import java.io.Serializable;
  4 import java.lang.reflect.Field;
  5 import java.util.ArrayList;
  6 import java.util.Collection;
  7 import java.util.List;
  8 import java.util.Map;
  9 import java.util.Map.Entry;
 10 
 11 import org.hibernate.Criteria;
 12 import org.hibernate.Query;
 13 import org.hibernate.QueryException;
 14 import org.hibernate.ScrollableResults;
 15 import org.hibernate.Session;
 16 import org.hibernate.SessionFactory;
 17 import org.hibernate.criterion.CriteriaSpecification;
 18 import org.hibernate.criterion.Criterion;
 19 import org.hibernate.criterion.DetachedCriteria;
 20 import org.hibernate.criterion.Order;
 21 import org.hibernate.criterion.Projections;
 22 import org.hibernate.criterion.Restrictions;
 23 import org.hibernate.internal.CriteriaImpl;
 24 import org.hibernate.internal.CriteriaImpl.Subcriteria;
 25 import org.hibernate.transform.Transformers;
 26 import org.springframework.beans.factory.annotation.Autowired;
 27 import org.springframework.transaction.annotation.Transactional;
 28 import org.springframework.util.Assert;
 29 
 30 import java.lang.reflect.ParameterizedType; 
 31 
 32 import com.github.pagehelper.PageInfo;
 33 import com.sxd.dao.GenericDao;
 34 
 35 public class GenericDaoImpl<T, PK extends Serializable> implements GenericDao<T, PK> {
 36     /**
 37      * 不建议直接使用
 38      */
 39     @Autowired
 40     private SessionFactory sessionFactory;
 41     
 42     public Session getSession() {
 43         // 需要开启事物,才能得到CurrentSession
 44         return sessionFactory.getCurrentSession();
 45     }
 46     
 47     
 48     protected Class<T> entityClass;
 49 
 50     protected Class getEntityClass() {
 51         if (entityClass == null) {
 52             if(((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments().length > 0) {
 53                 entityClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
 54             }
 55         }
 56         return entityClass;
 57     }
 58 
 59     public SessionFactory getSessionFactory() {
 60         return sessionFactory;
 61     }
 62     
 63     public void setSessionFactory(SessionFactory sessionFactory) {
 64         this.sessionFactory = sessionFactory;
 65     }
 66     
 67     @Override
 68     public Criteria createCriteria() {
 69         return getSession().createCriteria(getEntityClass());
 70     }
 71 
 72     
 73     @Override
 74     public void save(T t) {
 75         this.getSession().save(t);
 76     }
 77 
 78     @Override
 79     public void saveOrUpdate(T t) {
 80         Assert.notNull(t);
 81         this.getSession().saveOrUpdate(t);
 82     }
 83     
 84     @Override
 85     public T load(PK id) {
 86         Assert.notNull(id);
 87         T load = (T) this.getSession().load(getEntityClass(), id);
 88         return load;
 89     }
 90 
 91     @Override
 92     public T get(PK id) {
 93         T load = (T) this.getSession().get(getEntityClass(), id);
 94         return load;
 95     }
 96 
 97     @Override
 98     public boolean contains(T t) {
 99         Assert.notNull(t);
100         return this.getSession().contains(t);
101     }
102 
103     @Override
104     public void delete(T t) {
105         Assert.notNull(t);
106         this.getSession().delete(t);
107     }
108 
109     @Override
110     public boolean deleteById(PK Id) {
111         Assert.notNull(Id);
112         T t = get(Id);
113         if (t == null) return false;
114         delete(t);
115         return true;
116     }
117 
118     @Override
119     public void deleteAll(Collection<T> entities) {
120         Assert.notNull(entities);
121         for (Object entity : entities) {
122             this.getSession().delete(entity);
123         }
124     }
125 
126     @Override
127     public void queryHql(String hqlString, Object... values) {
128         Query query = this.getSession().createQuery(hqlString);
129         if (values != null) {
130             for (int i = 0; i < values.length; i++) {
131                 query.setParameter(i, values[i]);
132             }
133         }
134         query.executeUpdate();
135     }
136     
137     /**
138      * 根据hql  和    map集合中的数据   进行相对应的 insert   update   delete操作
139      * @param hqlString
140      * @param paras
141      */
142     public void queryHql(String hqlString, Map<String, Object> paras) {
143         Query query = this.getSession().createQuery(hqlString);
144         if (paras != null) {
145             for (Entry<String, Object> en : paras.entrySet()) {
146                 query.setParameter(en.getKey(), en.getValue());
147             }
148         }
149         query.executeUpdate();
150     }
151 
152     @Override
153     public void querySql(String sqlString, Object... values) {
154         Query query = this.getSession().createSQLQuery(sqlString);
155         if (values != null) {
156             for (int i = 0; i < values.length; i++) {
157                 query.setParameter(i, values[i]);
158             }
159         }
160         query.executeUpdate();
161     }
162 
163     @Override
164     public T getByHQL(String hqlString, Object... values) {
165         Query query = this.getSession().createQuery(hqlString);
166         if (values != null) {
167             for (int i = 0; i < values.length; i++) {
168                 query.setParameter(i, values[i]);
169             }
170         }
171         return (T) query.uniqueResult();
172     }
173 
174     @Override
175     public List<T> getListByHQL(String hqlString, Object... values) {
176         Query query = this.getSession().createQuery(hqlString);
177         if (values != null) {
178             for (int i = 0; i < values.length; i++) {
179                 query.setParameter(i, values[i]);
180             }
181         }
182         return query.list();
183     }
184 
185     @Override
186     public List<T> getListBySQL(String sqlString,Class c, Object... values) {
187         Query query = this.getSession().createSQLQuery(sqlString);
188         if (values != null) {
189             for (int i = 0; i < values.length; i++) {
190                 query.setParameter(i, values[i]);
191             }
192         }
193         query.setResultTransformer(Transformers.aliasToBean(c));
194         return query.list();
195     }
196 
197     @Override
198     public void refresh(T t) {
199         this.getSession().refresh(t);
200     }
201 
202     @Override
203     public void update(T t) {
204         this.getSession().update(t);
205     }
206 
207     @Override
208     public Long countByHql(String hql, Object... values) {
209         Query query = this.getSession().createQuery(hql);
210         if (values != null) {
211             for (int i = 0; i < values.length; i++) {
212                 query.setParameter(i, values[i]);
213             }
214         }
215         return (Long) query.uniqueResult();
216     }
217 
218     @Override
219     public PageInfo<T> findPageByHql(String hql, String countHql, int pageNo, int pageSize, Object... values) {
220         PageInfo<T> retValue = new PageInfo<T>();
221         Query query = this.getSession().createQuery(hql);
222         if (values != null) {
223             for (int i = 0; i < values.length; i++) {
224                 query.setParameter(i, values[i]);
225             }
226         }
227         int currentPage = pageNo > 1 ? pageNo : 1;
228         retValue.setPages(currentPage);
229         retValue.setPageSize(pageSize);
230         if (countHql == null) {
231             ScrollableResults results = query.scroll();
232             results.last();
233             retValue.setTotal(results.getRowNumber() + 1);
234         } else {
235             Long count = countByHql(countHql, values);
236             retValue.setTotal(count.intValue());
237         }
238         List<T> itemList = query.setFirstResult((currentPage - 1) * pageSize).setMaxResults(pageSize).list();
239         if (itemList == null) {
240             itemList = new ArrayList<T>();
241         }
242         retValue.setList(itemList);
243         return retValue;
244     }
245 
246 
247     @Override
248     public void merge(T entity) {
249         // TODO Auto-generated method stub
250         getSession().merge(entity);
251     }
252     
253     @Override
254     public boolean exists(PK id) {
255         return null != get(id);
256     }
257 
258     @Override
259     public int countAll() {
260         Criteria criteria = createCriteria();
261         return Integer.valueOf(criteria.setProjection(Projections.rowCount()).uniqueResult().toString());
262     }
263 
264     @Override
265     public int countAll(Criteria criteria) {
266         criteria.setProjection(null);
267         return Integer.valueOf(criteria.setProjection(Projections.rowCount()).uniqueResult().toString());
268     }
269     
270     @Override
271     public List<T> list(Criteria criteria) {
272         return criteria.list();
273     }
274 
275     @Override
276     public List<T> list(DetachedCriteria criteria) {
277         return (List<T>) list(criteria.getExecutableCriteria(getSession()));
278     }
279 
280     @Override
281     public List<T> list(String orderBy, boolean isAsc) {
282         Criteria criteria = createCriteria();
283         if (isAsc) {
284             criteria.addOrder(Order.asc(orderBy));
285         } else {
286             criteria.addOrder(Order.desc(orderBy));
287         }
288         return criteria.list();
289     }
290     
291     @Override
292     public List<T> list(String propertyName, Object value) {
293         Criterion criterion = Restrictions.like(propertyName, "%"+ value +"%");
294         return list(criterion);
295     }
296 
297 
298     @Override
299     public List<T> list(Criterion criterion) {
300         Criteria criteria = createCriteria();
301         criteria.add(criterion);
302         return criteria.list();
303     }
304 
305     @Override
306     public List<T> list(Criterion... criterions) {
307         return createCriteria(criterions).list();
308     }
309 
310     @Override
311     public T uniqueResult(String propertyName, Object value) {
312         Criterion criterion = Restrictions.eq(propertyName, value);
313         return (T) createCriteria(criterion).uniqueResult();
314     }
315 
316     @Override
317     public T uniqueResult(Criterion... criterions) {
318         Criteria criteria = createCriteria(criterions);
319         return uniqueResult(criteria);
320     }
321 
322     @Override
323     public T uniqueResult(Criteria criteria) {
324         return (T) criteria.uniqueResult();
325     }
326     
327     @Override
328     public Integer uniqueResultInt(Criteria criteria) {
329         return (Integer) criteria.uniqueResult();
330     }
331 
332 
333     @Override
334     public Criteria distinct(Criteria criteria) {
335         criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
336         return criteria;
337     }
338 
339     @Override
340     public void flush() {
341         getSession().flush();
342     }
343 
344     @Override
345     public void clear() {
346         getSession().clear();
347     }
348 
349 
350     @Override
351     public Criteria createCriteria(Criterion... criterions) {
352         Criteria criteria = createCriteria();
353         for (Criterion c : criterions) {
354             criteria.add(c);
355         }
356         return criteria;
357     }
358 
359     @Override
360     public List<T> findPage(Criteria criteria, int pageNo, int pageSize) {
361         criteria.setFirstResult((pageNo - 1) * pageSize);
362         criteria.setMaxResults(pageSize);
363         return list(criteria);
364     }
365 
366     @Override
367     public PageInfo<T> findQuery(Criteria criteria, int pageNo, int pageSize) {
368         try {
369             Assert.isTrue(pageNo >= 1, "pageNO should start from 1");
370             while(criteria instanceof Subcriteria){
371                 criteria = ((Subcriteria)criteria).getParent();
372             }
373             //拆分order by子句  
374             while(criteria instanceof Subcriteria){
375                 criteria = ((Subcriteria)criteria).getParent();
376             }
377             Field field = CriteriaImpl.class.getDeclaredField("orderEntries");  
378             field.setAccessible(true);  
379             List<?> orderEntrys = (List<?>) field.get(criteria);  
380             field.set(criteria, new ArrayList());  
381             //统计总数
382             long totalCount = countAll(criteria);
383             criteria.setProjection(null);
384             //统计完了再把order by子句加上 这样保证了sql语句不会出错
385             field.set(criteria, orderEntrys);
386             List<T> list = findPage(criteria, pageNo, pageSize);
387             if (totalCount < 1) {
388                 return new PageInfo<T>();
389             }
390             PageInfo<T> page = new PageInfo<T>();
391             page.setPageNum(pageNo);
392             page.setTotal(totalCount);
393             page.setPages((int) (totalCount % pageSize == 0 ? totalCount / pageSize : totalCount / pageSize + 1));
394             page.setPageSize(pageSize);
395             page.setList(list);
396             return page;
397         } catch (Exception e) {
398             // TODO: handle exception
399             e.printStackTrace();
400             throw new QueryException("查询出错!");
401         }
402         
403     }
404 
405     @Override
406     public List<T> findQuery(String hql, int pageNo, int pageSize, Map<?, ?> map) {
407         // TODO Auto-generated method stub
408         if(null == hql) return null;
409         Query query = getSession().createQuery(hql);
410         for (Entry<?, ?> en : map.entrySet()) {
411             query.setParameter(en.getKey().toString(), en.getValue());
412         }
413         if(pageNo > 0) query.setFirstResult(pageNo);
414         if(pageSize > 0) query.setFirstResult(pageSize);
415         return query.list();
416     }
417 
418     @Override
419     public List<T> findAll() {
420         // TODO Auto-generated method stub
421         return createCriteria().list();
422     }
423 }
View Code

GenericService.java

【shiro】2.spring整合shiro,注解控制shiro用户/角色/权限And/OR,没有权限跳转到固定页面【shiro】2.spring整合shiro,注解控制shiro用户/角色/权限And/OR,没有权限跳转到固定页面
  1 package com.sxd.service;
  2 
  3 import java.io.Serializable;
  4 import java.util.Collection;
  5 import java.util.List;
  6 import java.util.Map;
  7 
  8 import org.hibernate.Criteria;
  9 import org.hibernate.criterion.Criterion;
 10 import org.hibernate.criterion.DetachedCriteria;
 11 
 12 import com.github.pagehelper.PageInfo;
 13 
 14 public interface GenericService<T, PK extends Serializable> {
 15     /**
 16      * 查询全部,可以排序
 17      * @param orderBy
 18      * @param isAsc
 19      * @return List<T>
 20      */
 21     public List<T> list(Criteria criteria);
 22 
 23     /**
 24      * 查询全部,可以排序
 25      * @param orderBy
 26      * @param isAsc
 27      * @return List<T>
 28      */
 29     public List<T> list(String orderBy, boolean isAsc);
 30     
 31     /**
 32      * 离线查询
 33      * @param criteria
 34      * @return List<T>
 35      */
 36     public List<T> list(DetachedCriteria criteria);
 37     
 38     /**
 39      * 根据Criteria查询条件,获取总数
 40      * @param criteria
 41      * @return int
 42      * @throws SecurityException 
 43      * @throws NoSuchFieldException 
 44      * @throws IllegalAccessException 
 45      * @throws IllegalArgumentException 
 46      */
 47     public int countAll(Criteria criteria);
 48     
 49     /**
 50      * 获取总数(默认为entityClass) 即查询总条数
 51      * @return int
 52      */
 53     public int countAll();
 54     
 55     /**
 56      * 根据I判断是否存在
 57      * @param id
 58      * @return boolean
 59      */
 60     public boolean exists(PK id);
 61     
 62     /**
 63      * 保存实体 
 64      * @param t 实体参数
 65      */
 66     public void save(T t);
 67 
 68     /**
 69      * 保存或者更新实体
 70      * @param t 实体
 71      */
 72     public void saveOrUpdate(T t);
 73 
 74     /**
 75      * 加载实体的通过load方法
 76      * @param id 实体的id
 77      * @return 查询出来的实体
 78      */
 79     public T load(PK id);
 80     
 81     /**
 82      * 合并实体 
 83      * @param entity
 84      */
 85     public void merge(T entity);
 86     
 87     /**
 88      * 查找全部
 89      */
 90     public List<T> findAll();
 91 
 92     /**
 93      * 通过get方法加载实体的
 94      * @param id 实体的id
 95      * @return 查询出来的实体
 96      */
 97     public T get(PK id);
 98 
 99     /**
100      * contains
101      * @param t 实体
102      * @return 是否包含
103      */
104     public boolean contains(T t);
105 
106     /**
107      * delete
108      * @param t
109      * 删除实体
110      */
111     public void delete(T t);
112 
113     /**
114      * 根据ID删除数据
115      * @param Id 实体id
116      * @return 是否删除成功
117      */
118     public boolean deleteById(PK Id);
119 
120     /**
121      * 删除所有
122      * @param entities 实体的Collection集合
123      */
124     public void deleteAll(Collection<T> entities);
125 
126     /**
127      * 执行Hql语句 要求 hql中参数顺序与可变参数 中参数顺序相一致
128      * @param hqlString hql
129      * @param values 不定参数数组
130      */
131     public void queryHql(String hqlString, Object... values);
132 
133     /**
134      * 执行Sql语句(不建议用,影响扩展)
135      * @param sqlString sql
136      * @param values 不定参数数组
137      */
138     public void querySql(String sqlString, Object... values);
139 
140     /**
141      * 根据HQL语句查找唯一实体
142      * 
143      * @param hqlString HQL语句
144      * @param values 不定参数的Object数组
145      * @return 查询实体
146      */
147     public T getByHQL(String hqlString, Object... values);
148     
149     /**
150      * 根据SQL语句查找唯一实体(不建议用,影响扩展)
151      * @param sqlString SQL语句
152      * @param values 不定参数的Object数组
153      * @return 查询实体
154      */
155 
156     /**
157      * 根据HQL语句,得到对应的list
158      * @param hqlString HQL语句
159      * @param values 不定参数的Object数组
160      * @return 查询多个实体的List集合
161      */
162     public List<T> getListByHQL(String hqlString, Object... values);
163 
164     /**
165      * 根据SQL语句,得到对应的list(不建议用,影响扩展)
166      * @param sqlString HQL语句
167      * @param values 不定参数的Object数组
168      * @return 查询多个实体的List集合
169      */
170     public List<T> getListBySQL(String sqlString,Class c, Object... values);
171 
172     /**
173      * refresh 刷新实体,强制与数据库两步 refresh方法应该是数据库的数据更新到本地的person实体中,而不是本地person更新数据到数据库中  也就是执行refresh方法是更新了java代码中变量的数据值
174      * @param t 实体
175      */
176     public void refresh(T t);
177 
178     /**
179      * update
180      * @param t
181      * 更新的是数据库中的数据
182      */
183     public void update(T t);
184 
185     /**
186      * 根据HQL得到记录数
187      * @param hql HQL语句
188      * @param values 不定参数的Object数组
189      * @return 记录总数
190      */
191     public Long countByHql(String hql, Object... values);
192 
193     /**
194      * HQL分页查询
195      * 
196      * @param hql HQL语句
197      * @param countHql 查询记录条数的HQL语句
198      * @param pageNo 下一页
199      * @param pageSize 一页总条数
200      * @param values  不定Object数组参数
201      * @return PageResults的封装类,里面包含了页码的信息以及查询的数据List集合
202      */
203     public  PageInfo<T> findPageByHql(String hql, String countHql, int pageNo, int pageSize, Object... values);
204     
205     /**
206      * 按属性查找对象列表,匹配方式为相等
207      * @param propertyName
208      * @param value
209      * @return List<T>
210      */
211     public List<T> list(String propertyName, Object value);
212     
213     /**
214      * 根据criterion查询条件获取数据列表
215      * @param criterion
216      * @return List<T>
217      */
218     public List<T> list(Criterion criterion);
219     
220     /**
221      * 按Criteria查询对象列表
222      * @param criterions
223      * @return List<T>
224      */
225     public List<T> list(Criterion... criterions);
226     
227     /**
228      * 按属性查找唯一对象,匹配方式为相等
229      * @param propertyName
230      * @param value
231      * @return T
232      */
233     public T uniqueResult(String propertyName, Object value);
234     
235     /**
236      * 按Criteria查询唯一对象
237      * @param criterions
238      * @return T
239      */
240     public T uniqueResult(Criterion... criterions);
241     
242     /**
243      * 按Criteria查询唯一对象
244      * @param criteria
245      * @return T
246      */
247     public T uniqueResult(Criteria criteria);
248     /**
249      * 按照criteria返回类型为Integer类型的某个字段的值
250      * @param criteria
251      * @return
252      */
253     public Integer uniqueResultInt(Criteria criteria);
254     
255     
256     
257     /**
258      * 为Criteria添加distinct transformer
259      * @param criteria
260      * @return Criteria
261      */
262     public Criteria distinct(Criteria criteria);
263     
264     /**
265      * 刷新session
266      */
267     public void flush();
268     
269     /**
270      * 清空session
271      */
272     public void clear();
273     
274     /**
275      * 创建Criteria实例
276      */
277     public Criteria createCriteria();
278     
279     /**
280      * 根据Criterion条件创建Criteria
281      * @param criterions
282      * @return Criteria
283      */
284     public Criteria createCriteria(Criterion... criterions);
285     
286     /**
287      * 分页查询Criteria
288      * @param criteria 
289      * @param pageNo 下页页码
290      * @param pageSize 页面数据量
291      * @return List<T>
292      */
293     public List<T> findPage(Criteria criteria, int pageNo, int pageSize);
294     
295     /**
296      * 分页查询Criteria
297      * @param criteria
298      * @param pageNo
299      * @param pageSize
300      * @return PageInfo<T>
301      * @throws SecurityException 
302      * @throws NoSuchFieldException 
303      * @throws IllegalAccessException 
304      * @throws IllegalArgumentException 
305      */
306     public PageInfo<T> findQuery(Criteria criteria, int pageNo, int pageSize);
307     
308     /**
309      * 
310      * @param hql
311      * @param pageNo
312      * @param pageSize
313      * @param map
314      * @return List<T>
315      */
316     public List<T> findQuery(String hql, int pageNo, int pageSize, Map<?, ?> map);
317 
318 }
View Code

GenericServiceImpl.java

【shiro】2.spring整合shiro,注解控制shiro用户/角色/权限And/OR,没有权限跳转到固定页面【shiro】2.spring整合shiro,注解控制shiro用户/角色/权限And/OR,没有权限跳转到固定页面
  1 package com.sxd.service.impl;
  2 
  3 import java.io.Serializable;
  4 import java.util.Collection;
  5 import java.util.List;
  6 import java.util.Map;
  7 
  8 import org.hibernate.Criteria;
  9 import org.hibernate.criterion.Criterion;
 10 import org.hibernate.criterion.DetachedCriteria;
 11 import org.springframework.beans.factory.annotation.Autowired;
 12 import org.springframework.stereotype.Component;
 13 import org.springframework.stereotype.Service;
 14 import org.springframework.transaction.annotation.Propagation;
 15 import org.springframework.transaction.annotation.Transactional;
 16 
 17 import com.github.pagehelper.PageInfo;
 18 import com.sxd.dao.impl.GenericDaoImpl;
 19 import com.sxd.service.GenericService;
 20 
 21 @Transactional
 22 public class GenericServiceImpl<T, PK extends Serializable> implements GenericService<T, PK> {
 23 
 24     
 25     private GenericDaoImpl<T, PK> dao;
 26     /**
 27      * 设值注入Dao
 28      * @param dao
 29      */
 30     @Autowired
 31     public void setDao(GenericDaoImpl<T, PK> dao) {
 32         this.dao = dao;
 33     }
 34     
 35     @Override
 36     @Transactional(propagation = Propagation.REQUIRED)
 37     public List<T> list(Criteria criteria) {
 38         // TODO Auto-generated method stub
 39         return dao.list(criteria);
 40     }
 41 
 42     @Override
 43     public List<T> list(String orderBy, boolean isAsc) {
 44         // TODO Auto-generated method stub
 45         return dao.list(orderBy, isAsc);
 46     }
 47 
 48     @Override
 49     public List<T> list(DetachedCriteria criteria) {
 50         // TODO Auto-generated method stub
 51         return dao.list(criteria);
 52     }
 53 
 54     @Override
 55     public int countAll(Criteria criteria) {
 56         // TODO Auto-generated method stub
 57         return dao.countAll(criteria);
 58     }
 59 
 60     @Override
 61     public int countAll() {
 62         // TODO Auto-generated method stub
 63         return dao.countAll();
 64     }
 65 
 66     @Override
 67     public boolean exists(PK id) {
 68         // TODO Auto-generated method stub
 69         return dao.exists(id);
 70     }
 71 
 72     @Override
 73     @Transactional(propagation = Propagation.REQUIRED)
 74     public void save(T t) {
 75         // TODO Auto-generated method stub
 76         dao.save(t);
 77     }
 78 
 79     @Override
 80     @Transactional(propagation = Propagation.REQUIRED)
 81     public void saveOrUpdate(T t) {
 82         // TODO Auto-generated method stub
 83         dao.saveOrUpdate(t);
 84     }
 85 
 86     @Override
 87     @Transactional(propagation = Propagation.REQUIRED)
 88     public T load(PK id) {
 89         // TODO Auto-generated method stub
 90         return dao.load(id);
 91     }
 92 
 93     @Override
 94     @Transactional(propagation = Propagation.REQUIRED)
 95     public void merge(T entity) {
 96         // TODO Auto-generated method stub
 97         dao.merge(entity);
 98     }
 99 
100     @Override
101     @Transactional(propagation = Propagation.REQUIRES_NEW)
102     public List<T> findAll() {
103         // TODO Auto-generated method stub
104         return dao.findAll();
105     }
106 
107     @Override
108     @Transactional(propagation = Propagation.REQUIRED)
109     public T get(PK id) {
110         // TODO Auto-generated method stub
111         return dao.get(id);
112     }
113 
114     @Override
115     public boolean contains(T t) {
116         // TODO Auto-generated method stub
117         return dao.contains(t);
118     }
119 
120     @Override
121     public void delete(T t) {
122         // TODO Auto-generated method stub
123         dao.delete(t);
124     }
125 
126     @Override
127     @Transactional(propagation = Propagation.REQUIRED)
128     public boolean deleteById(PK Id) {
129         // TODO Auto-generated method stub
130         return dao.deleteById(Id);
131     }
132 
133     @Override
134     @Transactional(propagation = Propagation.REQUIRED)
135     public void deleteAll(Collection<T> entities) {
136         // TODO Auto-generated method stub
137         dao.deleteAll(entities);
138     }
139 
140     @Override
141     public void queryHql(String hqlString, Object... values) {
142         // TODO Auto-generated method stub
143         dao.queryHql(hqlString, values);
144     }
145 
146     @Override
147     public void querySql(String sqlString, Object... values) {
148         // TODO Auto-generated method stub
149         dao.querySql(sqlString, values);
150     }
151 
152     @Override
153     public T getByHQL(String hqlString, Object... values) {
154         // TODO Auto-generated method stub
155         return dao.getByHQL(hqlString, values);
156     }
157 
158     @Override
159     public List<T> getListByHQL(String hqlString, Object... values) {
160         // TODO Auto-generated method stub
161         return dao.getListByHQL(hqlString, values);
162     }
163 
164     @Override
165     public List<T> getListBySQL(String sqlString,Class c, Object... values) {
166         // TODO Auto-generated method stub
167         return dao.getListBySQL(sqlString, c, values);
168     }
169 
170     @Override
171     public void refresh(T t) {
172         // TODO Auto-generated method stub
173         dao.refresh(t);
174     }
175 
176     @Override
177     @Transactional(propagation = Propagation.REQUIRED)
178     public void update(T t) {
179         // TODO Auto-generated method stub
180         dao.update(t);
181     }
182 
183     @Override
184     public Long countByHql(String hql, Object... values) {
185         // TODO Auto-generated method stub
186         return dao.countByHql(hql, values);
187     }
188 
189     @Override
190     public PageInfo<T> findPageByHql(String hql, String countHql, int pageNo,
191             int pageSize, Object... values) {
192         // TODO Auto-generated method stub
193         return dao.findPageByHql(hql, countHql, pageNo, pageSize, values);
194     }
195 
196     @Override
197     public List<T> list(String propertyName, Object value) {
198         // TODO Auto-generated method stub
199         return dao.list(propertyName, value);
200     }
201 
202     @Override
203     public List<T> list(Criterion criterion) {
204         // TODO Auto-generated method stub
205         return dao.list(criterion);
206     }
207 
208     @Override
209     public List<T> list(Criterion... criterions) {
210         // TODO Auto-generated method stub
211         return dao.list(criterions);
212     }
213 
214     @Override
215     public T uniqueResult(String propertyName, Object value) {
216         // TODO Auto-generated method stub
217         return dao.uniqueResult(propertyName, value);
218     }
219 
220     @Override
221     public T uniqueResult(Criterion... criterions) {
222         // TODO Auto-generated method stub
223         return dao.uniqueResult(criterions);
224     }
225 
226     @Override
227     @Transactional(propagation = Propagation.REQUIRED, readOnly = true)
228     public T uniqueResult(Criteria criteria) {
229         // TODO Auto-generated method stub
230         return dao.uniqueResult(criteria);
231     }
232     
233     @Override
234     @Transactional(propagation = Propagation.REQUIRED, readOnly = true)
235     public Integer uniqueResultInt(Criteria criteria){
236         return dao.uniqueResultInt(criteria);
237     }
238     
239     @Override
240     public Criteria distinct(Criteria criteria) {
241         // TODO Auto-generated method stub
242         return dao.distinct(criteria);
243     }
244 
245     @Override
246     public void flush() {
247         // TODO Auto-generated method stub
248         dao.flush();
249     }
250 
251     @Override
252     public void clear() {
253         // TODO Auto-generated method stub
254         dao.clear();
255     }
256 
257     @Override
258     public Criteria createCriteria() {
259         // TODO Auto-generated method stub
260         return dao.createCriteria();
261     }
262 
263     @Override
264     public Criteria createCriteria(Criterion... criterions) {
265         // TODO Auto-generated method stub
266         return dao.createCriteria(criterions);
267     }
268 
269     @Override
270     public List<T> findPage(Criteria criteria, int pageNo, int pageSize) {
271         // TODO Auto-generated method stub
272         return dao.findPage(criteria, pageNo, pageSize);
273     }
274 
275     @Override
276     public PageInfo<T> findQuery(Criteria criteria, int pageNo, int pageSize) {
277         // TODO Auto-generated method stub
278         return dao.findQuery(criteria, pageNo, pageSize);
279     }
280 
281     @Override
282     public List<T> findQuery(String hql, int pageNo, int pageSize, Map<?, ?> map) {
283         // TODO Auto-generated method stub
284         return dao.findQuery(hql, pageNo, pageSize, map);
285     }
286 
287 }
View Code

使用工具类生成实体的Dao/Service

CreateJava.java

【shiro】2.spring整合shiro,注解控制shiro用户/角色/权限And/OR,没有权限跳转到固定页面【shiro】2.spring整合shiro,注解控制shiro用户/角色/权限And/OR,没有权限跳转到固定页面
  1 package com.sxd.utils;
  2 
  3 import java.io.File;
  4 import java.io.FileWriter;
  5 import java.io.IOException;
  6 
  7 import org.junit.Test;
  8 
  9 public class CreateJava {
 10     
 11     @Test
 12     public void justCreateJava() throws IOException{
 13         File file = new File("F:/workspace2/shiro-first/src/main/java/com/sxd/entity");
 14         File []list = file.listFiles();
 15         for (File file2 : list) {
 16             String fileName = file2.getName().substring(0,file2.getName().lastIndexOf("."));
 17             createDao(fileName);
 18             createDaoImpl(fileName);
 19             createService(fileName);
 20             createServiceImpl(fileName);
 21         }
 22     }
 23     /**
 24      * 创建Dao层
 25      * @param fileName
 26      * @throws IOException 
 27      */
 28     public void createDao(String fileName) throws IOException{
 29         //拼接 DaoImpl内容
 30                 String content = "package com.sxd.dao;\r\n"
 31                         + "\r\n"
 32                         + "import com.sxd.entity."+fileName+";\r\n"
 33                         + "public interface "+fileName+"Dao extends GenericDao<"+fileName+", String> {\r\n"
 34                                 + "\r\n"
 35                                 + "}";
 36                 
 37                 //指定将Dao文件生成到对应的指定位置
 38                 FileWriter writer = new FileWriter(new File("F:/workspace2/shiro-first/src/main/java/com/sxd/dao/"+fileName+"Dao.java"));
 39                 writer.write(content);
 40                 writer.close();
 41     }
 42     
 43     /**
 44      * 创建DaoImpl层
 45      */
 46     public void createDaoImpl(String fileName) throws IOException{
 47         //拼接 DaoImpl内容
 48         String content = "package com.sxd.dao.impl;\r\n"
 49                 + "\r\n"
 50                 + "import org.springframework.stereotype.Repository;\r\n"
 51                 + "import com.sxd.dao."+fileName+"Dao;\r\n"
 52                 + "import com.sxd.entity."+fileName+";\r\n"
 53                 + "@Repository \r\n"
 54                 + "public class "+fileName+"DaoImpl extends GenericDaoImpl<"+fileName+", String> implements "+fileName+"Dao {\r\n"
 55                         + "\r\n"
 56                 + "}";
 57         
 58         //指定将DaoImpl文件生成到对应的指定位置
 59         FileWriter writer = new FileWriter(new File("F:/workspace2/shiro-first/src/main/java/com/sxd/dao/impl/"+fileName+"DaoImpl.java"));
 60         writer.write(content);
 61         writer.close();
 62     }
 63     
 64     /**
 65      * 创建 Service层
 66      * @param fileName
 67      * @throws IOException
 68      */
 69     public void createService(String fileName) throws IOException{
 70         //拼接Service内容
 71         String content = "package com.sxd.service;\r\n"
 72                 + "import com.sxd.entity."+fileName+";\r\n"
 73                 + "public interface "+fileName+"Service extends GenericService<"+fileName+", String> {\r\n"
 74                         + "\r\n"
 75                         + "}";
 76         
 77         FileWriter writer = new FileWriter(new File("F:/workspace2/shiro-first/src/main/java/com/sxd/service/"+fileName+"Service.java"));
 78         writer.write(content);
 79         writer.close();
 80     }
 81     
 82     /**
 83      * 创建ServiceImpl
 84      * @throws IOException 
 85      */
 86     public void createServiceImpl(String fileName) throws IOException{
 87         //拼接Service内容
 88                 String content = "package com.sxd.service.impl;\r\n"
 89                         + "import org.springframework.beans.factory.annotation.Autowired;\r\n"
 90                         + "import org.springframework.stereotype.Service;\r\n"
 91                         + "import com.sxd.dao."+fileName+"Dao;\r\n"
 92                         + "import com.sxd.entity."+fileName+";\r\n"
 93                         + "import com.sxd.service."+fileName+"Service;\r\n"
 94                         + "@Service \r\n"
 95                         + "public class "+fileName+"ServiceImpl extends GenericServiceImpl<"+fileName+", String> implements "+fileName+"Service {\r\n"
 96                                 + "\r\n"
 97                                 + "@Autowired\r\n"
 98                                 + "private "+fileName+"Dao dao;\r\n"
 99                                 + "}";
100                 FileWriter writer = new FileWriter(new File("F:/workspace2/shiro-first/src/main/java/com/sxd/service/impl/"+fileName+"ServiceImpl.java"));
101                 writer.write(content);
102                 writer.close();
103     }
104     
105 }
View Code

 

6.配置spring+hibernate+shiro+springMVC的配置文件

【shiro】2.spring整合shiro,注解控制shiro用户/角色/权限And/OR,没有权限跳转到固定页面

config.properties

【shiro】2.spring整合shiro,注解控制shiro用户/角色/权限And/OR,没有权限跳转到固定页面【shiro】2.spring整合shiro,注解控制shiro用户/角色/权限And/OR,没有权限跳转到固定页面
 1 #application configs
 2 
 3 #jdbc c3p0 config
 4 jdbc.driver = com.mysql.jdbc.Driver
 5 jdbc.url = jdbc\:mysql\://localhost\:3306/shiros?useUnicode\=true&characterEncoding\=utf-8
 6 jdbc.username = root
 7 jdbc.password = root
 8 
 9 #hibernate config
10 hibernate.dialect = org.hibernate.dialect.MySQLDialect
11 hibernate.show_sql = true
12 hibernate.format_sql = false
13 hibernate.hbm2ddl.auto = update
14 hibernate.cache.use_second_level_cache = true
15 hibernate.cache.use_query_cache = true
16 hibernate.cache.region.factory_class = org.hibernate.cache.ehcache.EhCacheRegionFactory
17 hibernate.cache.provider_configuration_file_resource_path =ehcache.xml
View Code

ehcache.xml

【shiro】2.spring整合shiro,注解控制shiro用户/角色/权限And/OR,没有权限跳转到固定页面【shiro】2.spring整合shiro,注解控制shiro用户/角色/权限And/OR,没有权限跳转到固定页面
 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
 3     <diskStore path="D:/ehcache" />
 4     <!-- DefaultCache setting. -->
 5      <defaultCache
 6             maxElementsInMemory="1000"
 7             eternal="false"
 8             timeToIdleSeconds="120"
 9             timeToLiveSeconds="120"
10             maxElementsOnDisk="1000000"
11             overflowToDisk="true" 
12             memoryStoreEvictionPolicy="LRU">
13             
14     </defaultCache>
15 
16     <!-- Special objects setting. -->
17 
18     <cache 
19          name="org.andy.work.entity.AcctUser"
20          maxElementsInMemory="2"
21          memoryStoreEvictionPolicy="LRU" 
22          eternal="true" 
23          diskPersistent="false"
24          overflowToDisk="false" 
25          maxElementsOnDisk="1000000" /> 
26 
27 
28 
29 </ehcache>
View Code

log4j.properties

【shiro】2.spring整合shiro,注解控制shiro用户/角色/权限And/OR,没有权限跳转到固定页面【shiro】2.spring整合shiro,注解控制shiro用户/角色/权限And/OR,没有权限跳转到固定页面
 1 ### set log levels ###
 2 log4j.rootLogger = INFO , C , D , E 
 3 
 4 ### console ###
 5 log4j.appender.C = org.apache.log4j.ConsoleAppender
 6 log4j.appender.C.Target = System.out
 7 log4j.appender.C.layout = org.apache.log4j.PatternLayout
 8 log4j.appender.C.layout.ConversionPattern = [shiro-first][%p] [%-d{yyyy-MM-dd HH:mm:ss}] %C.%M(%L) | %m%n
 9 
10 ### log file ###
11 log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
12 log4j.appender.D.File = ../logs/springmvc_hibernate_demo.log
13 log4j.appender.D.Append = true
14 log4j.appender.D.Threshold = INFO 
15 log4j.appender.D.layout = org.apache.log4j.PatternLayout
16 log4j.appender.D.layout.ConversionPattern = [shiro-first][%p] [%-d{yyyy-MM-dd HH:mm:ss}] %C.%M(%L) | %m%n
17 
18 ### exception ###
19 log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
20 log4j.appender.E.File = ../logs/biologyInfo_error.log 
21 log4j.appender.E.Append = true
22 log4j.appender.E.Threshold = ERROR 
23 log4j.appender.E.layout = org.apache.log4j.PatternLayout
24 log4j.appender.E.layout.ConversionPattern =[shiro-first][%p] [%-d{yyyy-MM-dd HH\:mm\:ss}] %C.%M(%L) | %m%n
View Code

 spring-hibernate.xml

【shiro】2.spring整合shiro,注解控制shiro用户/角色/权限And/OR,没有权限跳转到固定页面【shiro】2.spring整合shiro,注解控制shiro用户/角色/权限And/OR,没有权限跳转到固定页面
  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:tx="http://www.springframework.org/schema/tx"
  5     xmlns:aop="http://www.springframework.org/schema/aop"
  6     xmlns:context="http://www.springframework.org/schema/context"
  7     xmlns:mvc="http://www.springframework.org/schema/mvc"
  8     xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
  9         http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
 10         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
 11         http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
 12         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">
 13      
 14       <!-- 以下为SpringMVC配置 -->
 15     <mvc:annotation-driven>
 16         <!-- 返回json数据,@response使用 -->
 17         <mvc:message-converters register-defaults="true">
 18             <bean
 19                 class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
 20                 <property name="supportedMediaTypes">
 21                     <list>
 22                         <value>text/html;charset=UTF-8</value>
 23                         <value>application/json;charset=UTF-8</value>
 24                     </list>
 25                 </property>
 26 
 27             </bean>
 28         </mvc:message-converters>
 29     </mvc:annotation-driven>
 30     
 31         
 32     <!-- 自动扫描@Controller注入为bean -->
 33     <context:property-placeholder location="classpath:config.properties"/>
 34     <!-- 自动扫描@Controller注入为bean -->
 35     <context:component-scan base-package="com.agen" />
 36     
 37     <!-- 标明注解事务 -->
 38     <tx:annotation-driven transaction-manager="transactionManager" /> 
 39     
 40         
 41     <!-- 配置数据源 c3p0 -->
 42     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
 43         destroy-method="close">
 44         <property name="driverClass" value="${jdbc.driver}" />
 45         <property name="jdbcUrl" value="${jdbc.url}" />
 46         <property name="user" value="${jdbc.username}" />
 47         <property name="password" value="${jdbc.password}" />
 48 
 49         <!-- 请求超时时间 -->
 50         <property name="checkoutTimeout" value="30000" />
 51         <!-- 每60秒检查所有连接池中的空闲连接。默认值: 0,不检查 -->
 52         <property name="idleConnectionTestPeriod" value="30" />
 53         <!-- 连接数据库连接池最大空闲时间 -->
 54         <property name="maxIdleTime" value="30" />
 55         <!-- 连接池初始化连接数 -->
 56         <property name="initialPoolSize" value="5" />
 57         <property name="minPoolSize" value="5" />
 58         <property name="maxPoolSize" value="20" />
 59         <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。默认值: 3 -->
 60         <property name="acquireIncrement" value="5" />
 61     </bean>
 62 
 63     <!-- 配置hibernate的SessionFactory -->
 64     <bean id="sessionFactory"
 65         class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
 66         <!-- 注入数据源 相关信息看源码 -->
 67         <property name="dataSource" ref="dataSource" />
 68         <!-- hibernate配置信息 -->
 69         <property name="hibernateProperties">
 70             <props>
 71                 <prop key="hibernate.dialect">${hibernate.dialect}</prop>
 72                 <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
 73                 <prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
 74                 <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
 75 
 76                 <!-- 开启二级缓存 ehcache -->
 77                 <prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</prop>
 78                 <prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</prop>
 79                 <prop key="hibernate.cache.region.factory_class">${hibernate.cache.region.factory_class}</prop>
 80                 <prop key="hibernate.cache.provider_configuration_file_resource_path">${hibernate.cache.provider_configuration_file_resource_path}
 81                 </prop>
 82             </props>
 83         </property>
 84         <!-- 扫描hibernate注解配置的entity -->
 85         <property name="packagesToScan" value="com.agen.entity" />
 86     </bean>
 87 
 88     <!-- 配置事务管理器 -->
 89     <bean id="transactionManager"
 90         class="org.springframework.orm.hibernate4.HibernateTransactionManager">
 91         <property name="sessionFactory" ref="sessionFactory" />
 92     </bean>
 93     
 94      <!-- 自定义Realm 
 95     <bean id="myRealm" class="com.sxd.utils.MyRealm">
 96            <property name="sessionFactory" ref="sessionFactory" />
 97     </bean>-->
 98 
 99     <!-- 安全管理器 -->
100     <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">  
101       <property name="realm" ref="myRealm"/>  
102     </bean>  
103 
104     <!-- Shiro过滤器 -->
105     <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">  
106         <!-- Shiro的核心安全接口,这个属性是必须的 -->  
107         <property name="securityManager" ref="securityManager"/>
108         <!-- 身份认证失败,则跳转到登录页面的配置 -->  
109         <property name="loginUrl" value="/index.jsp"/>
110         <!-- 权限认证失败,则跳转到指定页面 -->  
111         <property name="unauthorizedUrl" value="/error.jsp"/>  
112         <!-- Shiro连接约束配置,即过滤链的定义 -->  
113         <property name="filterChainDefinitions" ref="filterChainDefinitions" />
114     </bean>  
115     <bean name="filterChainDefinitions" class="java.lang.String">
116         <constructor-arg>
117             <value>
118                 /=anon
119                 /index.jsp=anon
120                 /login/login1.htmls=anon
121                 /login/register.htmls=anon
122                 /js/** = anon
123                 /bootstrap/** = anon
124                 /css/** = anon
125                 /images/** = anon
126                 /layer/** = anon
127                 /lib/** = anon
128                 /skin/** = anon
129                 /temp/** = anon
130                 /upload/** = anon
131                 /**=authc 
132             </value>
133         </constructor-arg>
134     </bean>
135 
136     <!-- 保证实现了Shiro内部lifecycle函数的bean执行 -->  
137     <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>  
138 
139     <!-- 开启Shiro注解 -->
140     <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor">
141         <property name="proxyTargetClass" value="true"/> 
142     </bean>  
143     <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
144           <property name="securityManager" ref="securityManager"/>  
145     </bean>  
146     
147     <!-- 自定义异常处理-->
148     <bean id="exceptionResolver" class="com.agen.util.MyExceptionResolver"></bean> 
149     
150     
151 </beans>
View Code

 

着重注意shiro的相关配置:

 1   <!-- 自定义Realm 
 2     <bean id="myRealm" class="com.sxd.utils.MyRealm">
 3            <property name="sessionFactory" ref="sessionFactory" />
 4     </bean>-->
 5 
 6     <!-- 安全管理器 -->
 7     <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">  
 8       <property name="realm" ref="myRealm"/>  
 9     </bean>  
10 
11     <!-- Shiro过滤器 -->
12     <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">  
13         <!-- Shiro的核心安全接口,这个属性是必须的 -->  
14         <property name="securityManager" ref="securityManager"/>
15         <!-- 身份认证失败,则跳转到登录页面的配置 -->  
16         <property name="loginUrl" value="/index.jsp"/>
17         <!-- 权限认证失败,则跳转到指定页面 -->  
18         <property name="unauthorizedUrl" value="/error.jsp"/>  
19         <!-- Shiro连接约束配置,即过滤链的定义 -->  
20         <property name="filterChainDefinitions" ref="filterChainDefinitions" />
21     </bean>  
22     <bean name="filterChainDefinitions" class="java.lang.String">
23         <constructor-arg>
24             <value>
25                 /=anon
26                 /index.jsp=anon
27                 /login/login1.htmls=anon
28                 /login/register.htmls=anon
29                 /js/** = anon
30                 /bootstrap/** = anon
31                 /css/** = anon
32                 /images/** = anon
33                 /layer/** = anon
34                 /lib/** = anon
35                 /skin/** = anon
36                 /temp/** = anon
37                 /upload/** = anon
38                 /**=authc 
39             </value>
40         </constructor-arg>
41     </bean>
42 
43     <!-- 保证实现了Shiro内部lifecycle函数的bean执行 -->  
44     <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>  
45 
46     <!-- 开启Shiro注解 -->
47     <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor">
48         <property name="proxyTargetClass" value="true"/> 
49     </bean>  
50     <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
51           <property name="securityManager" ref="securityManager"/>  
52     </bean>  
53     
54     <!-- 自定义异常处理-->
55     <bean id="exceptionResolver" class="com.agen.util.MyExceptionResolver"></bean> 

 

其中:1>shiro需要开启注解

   2>shiro自定义异常处理【这个自定义的异常处理类需要自己写】

     3>/=anon表示跟路径【http://localhost:8080/shiro-first/】是不拦截的

   4>/index.jsp=anon表示【http://localhost:8080/shiro-first/index.jsp】是不拦截的

   5>/js/** = anon表示【http://localhost:8080/shiro-first/js/jquery.js】这种类型的资源请求都是不拦截的

   6>/**=authc 表示除了上面定义的不拦截之外的其他请求地址均需要被拦截到,被拦截到是需要验证 当前访问这个地址的 用户是否已经通过验证,也就是是否登录过,如果没有,会根据上面配置的<property name="loginUrl" value="/index.jsp"/>跳转指定页面,这里就是指定到登录页面。

   7><property name="unauthorizedUrl" value="/error.jsp"/>如果没有整合使用springMVC跳转页面,那么这个就是有用的,现在页面的跳转交给springMVC来控制,这个权限认证不通过的配置就不起作用了,而是springMVC根据抛出异常,然后根据自定义的异常处理类,跳转到指定的页面了。

   8>

<!-- 自定义Realm 
    <bean id="myRealm" class="com.sxd.utils.MyRealm">
           <property name="sessionFactory" ref="sessionFactory" />
    </bean>-->

   自定义的这个Realm相当于咱们自己写的Filter,其中是实现了shiro提供的接口,进行了相对应的处理,拿到了本用户以及本用户所对应的权限,交给shiro自行比较,完成验证。

   9>/login/login.htmls=anon需要加后缀是因为web.xml中的相关配置未拦截到相关的请求页面,仅注意就好

spring-mvc.xml

【shiro】2.spring整合shiro,注解控制shiro用户/角色/权限And/OR,没有权限跳转到固定页面【shiro】2.spring整合shiro,注解控制shiro用户/角色/权限And/OR,没有权限跳转到固定页面
 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:mvc="http://www.springframework.org/schema/mvc"
 4     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 5     xmlns:p="http://www.springframework.org/schema/p"
 6     xmlns:context="http://www.springframework.org/schema/context"
 7     xmlns:tx="http://www.springframework.org/schema/tx"
 8     xmlns:aop="http://www.springframework.org/schema/aop"
 9     xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
10         http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
11         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
12         http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
13         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">
14 
15 
16        <!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 -->
17         <bean
18             class="org.springframework.web.servlet.view.InternalResourceViewResolver">
19             <property name="viewClass"
20                 value="org.springframework.web.servlet.view.JstlView" />
21             <property name="prefix" value="/WEB-INF/views" />
22             <property name="suffix" value=".jsp" />
23         </bean>
24     
25 
26     <!-- 实现文件上传,这样一旦某个Request是一个MultipartRequest,它就会首先被MultipartResolver处理,然后再转发相应的Controller -->
27     <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
28          <!-- 设置上传文件的最大尺寸为1GB -->
29          <!-- <property name="maxUploadSize">
30           <value>1073741824</value>
31          </property> -->
32     </bean>
33     
34 </beans>
View Code

 

 7.配置web项目的web.xml文件

【shiro】2.spring整合shiro,注解控制shiro用户/角色/权限And/OR,没有权限跳转到固定页面【shiro】2.spring整合shiro,注解控制shiro用户/角色/权限And/OR,没有权限跳转到固定页面
 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 3     xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
 4     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
 5     id="WebApp_ID" version="2.5">
 6 <!-- web容器是web项目的大脑 -->
 7 <!-- 在web.xml中,执行顺序是:1.先执行listener 2。再执行filter  3.最后执行servlet 这就是执行顺序 
 8     就像spring-hibernate.xml文件是在执行Listener的时候加载的,那注意这几个配置文件在web.xml中的加载顺序,因为资源文件是在配置文件【xml文件】中加载的,肯定是先加载的资源文件【properties文件】,才能在配置文件中调用资源文件中的变量的值使用
 9 
10  -->
11     <display-name>shiro-first</display-name>
12 <!-- web容器,首先需要引入spring,让spring管理各个框架,并将其注入为bean -->
13 <!-- 这个相当于定一个 变量在web.xml中,在下面的listener  org.springframework.web.context.ContextLoaderListener中,加载这个spring-hibernate.xml文件 -->
14     <context-param>
15         <param-name>contextConfigLocation</param-name>
16         <param-value>classpath:spring-hibernate.xml</param-value>
17     </context-param>
18     
19 <!-- 编码过滤器 配置控制层的filter信息 -->
20     <filter>
21         <filter-name>encodingFilter</filter-name>
22         <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
23         <init-param>
24             <param-name>encoding</param-name>
25             <param-value>utf-8</param-value>
26         </init-param>
27         <init-param>
28             <param-name>forceEncoding</param-name>
29             <param-value>true</param-value>
30         </init-param>
31     </filter>
32     <filter-mapping>
33         <filter-name>encodingFilter</filter-name>
34         <url-pattern>/*</url-pattern>
35     </filter-mapping>
36 
37   
38 <!-- 监听servletContext,启动contextConfigLocation中的spring配置信息 -->
39     <listener>
40         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
41     </listener>
42 
43 
44     <!-- 防止spring内存溢出监听器   可用可不用-->
45     <listener>
46         <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
47     </listener>
48     
49     <!-- shiro 
50     <listener>
51         <listener-class>org.apache.shiro.web.env.EnvironmentLoaderListener</listener-class>
52     </listener>
53      -->
54      <filter>  
55         <filter-name>shiroFilter</filter-name>  
56         <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>  
57         <init-param>  
58             <!-- 该值缺省为false,表示生命周期由SpringApplicationContext管理,设置为true则表示由ServletContainer管理 -->  
59             <param-name>targetFilterLifecycle</param-name>  
60             <param-value>true</param-value>  
61         </init-param>  
62     </filter>  
63     <filter-mapping>  
64         <filter-name>shiroFilter</filter-name>  
65         <url-pattern>/*</url-pattern>  
66     </filter-mapping>  
67     
68 
69 <!-- 添加springmvc支持 -->
70 <!-- 类似与servlet 需要在web.xml中都需要配置一样,spring的思想是让这些servlet【controller也是servlet】继承了一个基础的servlet,那就只需在web.xml中配置一个servlet即可。 -->
71 <!-- 这个servlet和下面的servlet-mapping相配合使用,注明了所有的以.htmls结尾的请求都被截取到,去到servlet中去找相对应的方法 进行处理 -->
72     <servlet>
73         <description>spring mvc servlet</description>
74         <servlet-name>rest</servlet-name>
75         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
76         <init-param>
77             <param-name>contextConfigLocation</param-name>
78             <!-- 此处配置的是SpringMVC的配置文件 -->
79             <param-value>classpath:spring-mvc.xml</param-value>
80         </init-param>
81         <load-on-startup>1</load-on-startup>
82     </servlet>
83     <!-- 配置了springmvc拦截的url为以.htmls结尾的请求 -->
84     <servlet-mapping>
85         <servlet-name>rest</servlet-name>
86         <url-pattern>*.htmls</url-pattern>
87     </servlet-mapping>
88 
89     <!-- 配置session超时时间,单位分钟 -->
90     <session-config>
91         <session-timeout>30</session-timeout>
92     </session-config>
93     <!-- 欢迎界面 默认的项目访问界面 -->
94     <welcome-file-list>
95         <welcome-file>/index.jsp</welcome-file>
96     </welcome-file-list>
97 </web-app>
View Code

 

8.相关配置完成,然后,先把登录页面做出来

【shiro】2.spring整合shiro,注解控制shiro用户/角色/权限And/OR,没有权限跳转到固定页面

index.jsp【登录页面/主页面】

【shiro】2.spring整合shiro,注解控制shiro用户/角色/权限And/OR,没有权限跳转到固定页面【shiro】2.spring整合shiro,注解控制shiro用户/角色/权限And/OR,没有权限跳转到固定页面
 1 <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
 2 <!DOCTYPE html>
 3 <html>
 4 <head>
 5 <title>LOGIN VIEW</title>
 6 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 7 <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
 8 <body class="hold-transition skin-blue sidebar-mini">
 9     <h2 style="color:red " class="msg"></h2>
10     <form method="post">
11     userName:<input type="text" name="username"/><br/>
12     password:<input type="password" name="password"/><br/>
13     <button type="button">login</button>
14     </form>
15 </body>
16 
17     <script type="text/javascript" src="js/jquery.js"></script>
18     <!-- 使用ajax提交而不是用submit,避免了 重定向 302的状态码 -->
19     <script type="text/javascript">
20         $(document).ready(function(){
21             $("button").click(function(){
22             
23                 var username = $("input[name='username']").val();
24                 var password = $("input[name='password']").val();
25                  //提交给后台
26                  $.ajax({url:"login/login.htmls",
27                         dataType:'json',
28                         type:"post",
29                         data:{username:username,password:password},
30                         traditional:true,
31                         success:function(data){
32                             if(data == "success"){
33                                 location.href = "login/success.htmls";
34                             }else{
35                                 $(".msg").text(data);
36                             }
37                         }
38                  });
39             });
40                 
41         });
42     </script>
43 </html>
View Code

success.jsp【成功页面】

【shiro】2.spring整合shiro,注解控制shiro用户/角色/权限And/OR,没有权限跳转到固定页面【shiro】2.spring整合shiro,注解控制shiro用户/角色/权限And/OR,没有权限跳转到固定页面
 1 <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
 2 <!DOCTYPE html>
 3 <html>
 4 <head>
 5 <meta charset="utf-8">
 6 <meta http-equiv="X-UA-Compatible" content="IE=edge">
 7 <title>Admin  主页</title>
 8 <!-- Tell the browser to be responsive to screen width -->
 9 <meta
10     content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"
11     name="viewport">
12 
13 <body>
14     成功
15     <button type="button" class="123" onclick="logout()">退出</button>
16 </body>
17 
18 <script type="text/javascript">
19     function logout(){
20         location.href = "../login/logout.htmls";
21     }
22 </script>
23 </html>
View Code

noAuth.jsp【没有权限页面】

【shiro】2.spring整合shiro,注解控制shiro用户/角色/权限And/OR,没有权限跳转到固定页面【shiro】2.spring整合shiro,注解控制shiro用户/角色/权限And/OR,没有权限跳转到固定页面
 1 <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
 2 <!DOCTYPE html>
 3 <html>
 4 <head>
 5 <meta charset="utf-8">
 6 <title>没有权限页面</title>
 7 <!-- Tell the browser to be responsive to screen width -->
 8 <meta
 9     content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"
10     name="viewport">
11 
12 <body class="hold-transition skin-blue sidebar-mini">
13     没有权限
14 </body>
15 
16 
17 </html>
View Code

 

9.springMVC的Controller,控制页面跳转

LoginController.java

【shiro】2.spring整合shiro,注解控制shiro用户/角色/权限And/OR,没有权限跳转到固定页面【shiro】2.spring整合shiro,注解控制shiro用户/角色/权限And/OR,没有权限跳转到固定页面
  1 package com.sxd.controller;
  2 
  3 import javax.servlet.http.HttpServletRequest;
  4 import javax.servlet.http.HttpSession;
  5 
  6 import org.apache.shiro.SecurityUtils;
  7 import org.apache.shiro.authc.AuthenticationException;
  8 import org.apache.shiro.authc.IncorrectCredentialsException;
  9 import org.apache.shiro.authc.UnknownAccountException;
 10 import org.apache.shiro.authc.UsernamePasswordToken;
 11 import org.apache.shiro.authz.annotation.Logical;
 12 import org.apache.shiro.authz.annotation.RequiresGuest;
 13 import org.apache.shiro.authz.annotation.RequiresPermissions;
 14 import org.apache.shiro.authz.annotation.RequiresRoles;
 15 import org.apache.shiro.authz.annotation.RequiresUser;
 16 import org.apache.shiro.subject.Subject;
 17 import org.springframework.stereotype.Controller;
 18 import org.springframework.web.bind.annotation.RequestMapping;
 19 import org.springframework.web.bind.annotation.ResponseBody;
 20 
 21 @Controller
 22 @RequestMapping("login")
 23 public class LoginController {
 24     
 25     
 26     @RequestMapping("login")
 27     @ResponseBody
 28     public String login(String username,String password,HttpSession session){
 29         
 30         Subject subject = SecurityUtils.getSubject();
 31         UsernamePasswordToken token = new UsernamePasswordToken(username, password);
 32         String errorMsg = null;
 33         try {
 34             subject.login(token);
 35         } catch (UnknownAccountException e) {
 36             errorMsg = "用户名错误";
 37         }catch (IncorrectCredentialsException e) {
 38             errorMsg = "用户密码错误";
 39         }catch (AuthenticationException e) {
 40             errorMsg = "其它异常:"+e.getMessage();
 41         }
 42         
 43         if(errorMsg != null){
 44             System.out.println(errorMsg);
 45             return errorMsg;
 46         }
 47         return "success";
 48     }
 49     
 50     @RequestMapping("success")
 51     public String success(){
 52         return "/welcome/success";
 53     }
 54     
 55     
 56     @RequestMapping("/logout")
 57     public String logout(HttpServletRequest request) {
 58         request.getSession().invalidate();
 59         return "../../../index";
 60     }   
 61 
 62     /**
 63      * 当前登录用户   才能进入
 64      * @param request
 65      * @return
 66      */
 67     @RequestMapping("/user")
 68     @RequiresUser()
 69     public String admin(HttpServletRequest request) {
 70         return "/welcome/success";
 71     }
 72 
 73     @RequestMapping("/admin1")
 74     @RequiresRoles(value="管理员1")
 75     public String student1(HttpServletRequest request) {
 76         return "/welcome/success";
 77     }   
 78 
 79     /**
 80      * 没有用户/角色/权限 规定
 81      * @param request
 82      * @return
 83      */
 84     @RequestMapping("/admin")
 85     public String teacher1(HttpServletRequest request) {
 86         return "/welcome/success";
 87     }  
 88     /**
 89      * 角色为 这种角色的  才能进入
 90      * @param request
 91      * @return
 92      */
 93     @RequestMapping("/admin2")
 94     @RequiresRoles(value="管理员2")
 95     public String student2(HttpServletRequest request) {
 96         return "/welcome/success";
 97     }   
 98     /**
 99      * 仅满足这种权限的 可以进入
100      * @param request
101      * @return
102      */
103     @RequestMapping("/admin3")
104     @RequiresPermissions("疾病:增加")
105     public String teacher2(HttpServletRequest request) {
106         return "/welcome/success";
107     }  
108     /**
109      * 两种权限其中的一种满足 即满足
110      * @param request
111      * @return
112      */
113     @RequestMapping("/admin4")
114     @RequiresPermissions(value={"产品:增加","产品:修改"},logical=Logical.OR)
115     public String student3(HttpServletRequest request) {
116         return "/welcome/success";
117     }   
118     
119     /**
120      * 两种权限都满足 才满足
121      * @param request
122      * @return
123      */
124     @RequestMapping("/admin5")
125     @RequiresPermissions(value={"产品:增加","产品:修改"},logical=Logical.AND)
126     public String teacher3(HttpServletRequest request) {
127         return "/welcome/success";
128     }  
129     @RequestMapping("/admin6")
130     @RequiresPermissions(value="疾病:增加")
131     public String student4(HttpServletRequest request) {
132         return "/welcome/success";
133     }   
134     
135 }
View Code

其中 使用注解将权限/角色/用户 具体到某一个具体的方法上

 

10.自定义的Realm和自定义的异常控制处理类

【shiro】2.spring整合shiro,注解控制shiro用户/角色/权限And/OR,没有权限跳转到固定页面

 

MyRealm.java

【shiro】2.spring整合shiro,注解控制shiro用户/角色/权限And/OR,没有权限跳转到固定页面【shiro】2.spring整合shiro,注解控制shiro用户/角色/权限And/OR,没有权限跳转到固定页面
 1 package com.sxd.utils;
 2 
 3 import java.util.HashSet;
 4 import java.util.Set;
 5 
 6 import javax.annotation.Resource;
 7 
 8 import org.apache.shiro.authc.AuthenticationException;
 9 import org.apache.shiro.authc.AuthenticationInfo;
10 import org.apache.shiro.authc.AuthenticationToken;
11 import org.apache.shiro.authc.SimpleAuthenticationInfo;
12 import org.apache.shiro.authz.AuthorizationInfo;
13 import org.apache.shiro.authz.SimpleAuthorizationInfo;
14 import org.apache.shiro.realm.AuthorizingRealm;
15 import org.apache.shiro.subject.PrincipalCollection;
16 import org.hibernate.Criteria;
17 import org.hibernate.Session;
18 import org.hibernate.SessionFactory;
19 import org.hibernate.criterion.DetachedCriteria;
20 import org.hibernate.criterion.Restrictions;
21 import org.springframework.beans.factory.annotation.Autowired;
22 import org.springframework.stereotype.Component;
23 
24 import com.sxd.entity.Authority;
25 import com.sxd.entity.Role;
26 import com.sxd.entity.User;
27 import com.sxd.service.UserService;
28 
29 @Component(value="myRealm")
30 public class MyRealm extends AuthorizingRealm {
31 
32     
33     @Resource
34     private UserService userService;
35     @Autowired
36     private SessionFactory sessionFactory;
37     
38     public Session getSession() {
39         // 需要开启事物,才能得到CurrentSession
40         return sessionFactory.openSession();
41     }
42     
43     /**
44      * 用来为当前登陆成功的用户授予权限和角色(已经登陆成功了)
45      */
46     @Override
47     protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
48             String username = (String) principals.getPrimaryPrincipal(); //获取用户名
49             SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
50             //拼接criteria查询条件
51             Criteria criteria = getSession().createCriteria(User.class);
52             //根据用户名查询
53             criteria.add(Restrictions.eq("userName", username));
54             User user = userService.uniqueResult(criteria);
55             if(user != null){
56                 //获取到用户的角色,根据角色,封装数据为Set<String>,将可以唯一确定本条数据的信息封装起来,供shiro对比使用
57                 Role role= user.getRole(); 
58                 Set<String> roleSet = new HashSet<String>();
59                 roleSet.add(role.getRoleName());
60                 authorizationInfo.setRoles(roleSet);
61                 
62                 //同理,根据用户角色所拥有的权限,封装数据,将唯一确定本条权限信息的String封装为set,供shiro使用
63                 Set<Authority> authoritySet = role.getAuthorities();
64                 Set<String> auSet = new HashSet<String>();
65                 for (Authority authority : authoritySet) {
66                     auSet.add(authority.getAuthorityName());
67                 }
68                 authorizationInfo.setStringPermissions(auSet);
69                 return authorizationInfo;
70             }else{
71                 return null;
72             }
73             
74     }
75 
76     /**
77      * 用来验证当前登录的用户,获取认证信息 (对比是否可以成功登录)
78      */
79     @Override
80     protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
81         String username = (String) token.getPrincipal();//获取用户名
82         Criteria criteria = getSession().createCriteria(User.class);
83         criteria.add(Restrictions.eq("userName", username));
84         User user = userService.uniqueResult(criteria);
85         if(user != null){
86              AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(user.getUserName(), user.getPassword(), this.getName());
87              return authcInfo;
88         }else{
89             return null;
90         }
91     }
92 
93 }
View Code

MyExceptionResolver.java

【shiro】2.spring整合shiro,注解控制shiro用户/角色/权限And/OR,没有权限跳转到固定页面【shiro】2.spring整合shiro,注解控制shiro用户/角色/权限And/OR,没有权限跳转到固定页面
 1 package com.sxd.utils;
 2 
 3 import javax.servlet.http.HttpServletRequest;
 4 import javax.servlet.http.HttpServletResponse;
 5 
 6 import org.apache.shiro.authz.UnauthorizedException;
 7 import org.springframework.web.servlet.HandlerExceptionResolver;
 8 import org.springframework.web.servlet.ModelAndView;
 9 
10 /**
11  * 自定义 --异常处理类
12  * @author Administrator
13  *
14  */
15 public class MyExceptionResolver implements HandlerExceptionResolver {
16 
17     @Override
18     public ModelAndView resolveException(HttpServletRequest request,
19             HttpServletResponse response, Object handler, Exception ex) {
20         System.out.println("==============异常开始=============");
21         //如果是shiro无权操作,因为shiro 在操作auno等一部分不进行转发至无权限url
22         if(ex instanceof UnauthorizedException){
23             ModelAndView mv = new ModelAndView("/error/noAuth");//指定跳转到没有权限的页面
24             return mv;
25         }
26         ex.printStackTrace();
27         System.out.println("==============异常结束=============");
28         ModelAndView mv = new ModelAndView("error");
29         mv.addObject("exception", ex.toString().replaceAll("\n", "<br/>"));
30         return mv;
31     }
32 
33 }
View Code

 

11.项目搭建完成,启动tomcat

访问地址:http://localhost:8080/shiro-first/

【shiro】2.spring整合shiro,注解控制shiro用户/角色/权限And/OR,没有权限跳转到固定页面

 

用数据库中的某个用户登录:张三 123456

【shiro】2.spring整合shiro,注解控制shiro用户/角色/权限And/OR,没有权限跳转到固定页面

【shiro】2.spring整合shiro,注解控制shiro用户/角色/权限And/OR,没有权限跳转到固定页面

【shiro】2.spring整合shiro,注解控制shiro用户/角色/权限And/OR,没有权限跳转到固定页面

 

使用张三登录成功之后,张三的role是管理员1,管理员1对应的权限有疾病的增删改查,数据库中有

然后,此时张三登陆成功,

【shiro】2.spring整合shiro,注解控制shiro用户/角色/权限And/OR,没有权限跳转到固定页面

直接在地址栏修改地址为:http://localhost:8080/shiro-first/login/admin1.htmls

【shiro】2.spring整合shiro,注解控制shiro用户/角色/权限And/OR,没有权限跳转到固定页面

 

而更改地址为:http://localhost:8080/shiro-first/login/admin2.htmls

【shiro】2.spring整合shiro,注解控制shiro用户/角色/权限And/OR,没有权限跳转到固定页面

【shiro】2.spring整合shiro,注解控制shiro用户/角色/权限And/OR,没有权限跳转到固定页面

 

 同理 测试其他的地址 即可!!!!!

 

上一篇:机房收费系统之技术总结


下一篇:【shiro】spring整合shiro,注解控制shiro用户/角色/权限And/OR,没有权限跳转到固定页面