shiro框架使用demo

  1. 权限的简单描述
  2. 实例表结构及内容及POJO
  3. Shiro-pom.xml
  4. Shiro-web.xml
  5. Shiro-MyShiro-权限认证,登录认证层
  6. Shiro-applicationContext-shiro.xml
  7. HomeController
  8. 三个JSP文件
  什么是权限呢?举个简单的例子:
我有一个论坛,注册的用户分为normal用户,manager用户。
对论坛的帖子的操作有这些:
添加,删除,更新,查看,回复
我们规定:
normal用户只能:添加,查看,回复
manager用户可以:删除,更新

normal,manager对应的是角色(role)
添加,删除,更新等对应的是权限(permission)

我们采用下面的逻辑创建权限表结构(不是绝对的,根据需要修改)

一个用户可以有多种角色(normal,manager,admin等等)
一个角色可以有多个用户(user1,user2,user3等等)
一个角色可以有多个权限(save,update,delete,query等等)
一个权限只属于一个角色(delete只属于manager角色)



 

 我们创建四张表:
t_user用户表:设置了3个用户

-------------------------------
id + username   + password
---+----------------+----------
1  +   tom           +  000000
2  +   jack           +  000000
3  +   rose          +  000000
---------------------------------
t_role 角色表:设置3个角色
--------------
id + rolename 
---+----------
1  + admin
2  + manager
3  + normal
--------------
t_user_role 用户角色表:tom是admin和normal角色,jack是manager和normal角色,rose是normal角色
---------------------
user_id  +  role_id
-----------+-----------
1            +     1
1            +     3
2            +     2
2            +     3
3            +     3
---------------------
t_permission 权限表:admin角色可以删除,manager角色可以添加和更新,normal角色可以查看
-----------------------------------
id  +  permissionname  +  role_id
----+------------------------+-----------
1   +   add                     +     2
2   +   del                       +    1
3   +   update                +     2
4   +   query                   +    3
-----------------------------------

 

 建立对应的POJO:

Java代码   收藏代码
  1. [java]  view plain  copy
    1. package com.cn.pojo;    
    2.     
    3. import java.util.HashSet;    
    4. import java.util.List;    
    5. import java.util.Set;    
    6.     
    7. import javax.persistence.Entity;    
    8. import javax.persistence.GeneratedValue;    
    9. import javax.persistence.GenerationType;    
    10. import javax.persistence.Id;    
    11. import javax.persistence.JoinColumn;    
    12. import javax.persistence.JoinTable;    
    13. import javax.persistence.ManyToMany;    
    14. import javax.persistence.Table;    
    15. import javax.persistence.Transient;    
    16.     
    17. import org.hibernate.validator.constraints.NotEmpty;    
    18.     
    19. @Entity    
    20. @Table(name="t_user")    
    21. public class User {    
    22.     
    23.     private Integer id;    
    24.     @NotEmpty(message="用户名不能为空")    
    25.     private String username;    
    26.     @NotEmpty(message="密码不能为空")    
    27.     private String password;    
    28.     private List<Role> roleList;//一个用户具有多个角色    
    29.         
    30.     @Id    
    31.     @GeneratedValue(strategy=GenerationType.IDENTITY)    
    32.     public Integer getId() {    
    33.         return id;    
    34.     }    
    35.     public void setId(Integer id) {    
    36.         this.id = id;    
    37.     }    
    38.     public String getUsername() {    
    39.         return username;    
    40.     }    
    41.     public void setUsername(String username) {    
    42.         this.username = username;    
    43.     }    
    44.     public String getPassword() {    
    45.         return password;    
    46.     }    
    47.     public void setPassword(String password) {    
    48.         this.password = password;    
    49.     }    
    50.     @ManyToMany    
    51.     @JoinTable(name="t_user_role",joinColumns={@JoinColumn(name="user_id")},inverseJoinColumns={@JoinColumn(name="role_id")})    
    52.     public List<Role> getRoleList() {    
    53.         return roleList;    
    54.     }    
    55.     public void setRoleList(List<Role> roleList) {    
    56.         this.roleList = roleList;    
    57.     }    
    58.         
    59.     @Transient    
    60.     public Set<String> getRolesName(){    
    61.         List<Role> roles=getRoleList();    
    62.         Set<String> set=new HashSet<String>();    
    63.         for (Role role : roles) {    
    64.             set.add(role.getRolename());    
    65.         }    
    66.         return set;    
    67.     }    
    68.         
    69. }    
    70.    
    71. Java代码  收藏代码  
    72. package com.cn.pojo;    
    73.     
    74. import java.util.ArrayList;    
    75. import java.util.List;    
    76.     
    77. import javax.persistence.Entity;    
    78. import javax.persistence.GeneratedValue;    
    79. import javax.persistence.GenerationType;    
    80. import javax.persistence.Id;    
    81. import javax.persistence.JoinColumn;    
    82. import javax.persistence.JoinTable;    
    83. import javax.persistence.ManyToMany;    
    84. import javax.persistence.OneToMany;    
    85. import javax.persistence.Table;    
    86. import javax.persistence.Transient;    
    87.     
    88. @Entity    
    89. @Table(name="t_role")    
    90. public class Role {    
    91.     
    92.     private Integer id;    
    93.     private String rolename;    
    94.     private List<Permission> permissionList;//一个角色对应多个权限    
    95.     private List<User> userList;//一个角色对应多个用户    
    96.         
    97.     @Id    
    98.     @GeneratedValue(strategy=GenerationType.IDENTITY)    
    99.     public Integer getId() {    
    100.         return id;    
    101.     }    
    102.     public void setId(Integer id) {    
    103.         this.id = id;    
    104.     }    
    105.     public String getRolename() {    
    106.         return rolename;    
    107.     }    
    108.     public void setRolename(String rolename) {    
    109.         this.rolename = rolename;    
    110.     }    
    111.     @OneToMany(mappedBy="role")    
    112.     public List<Permission> getPermissionList() {    
    113.         return permissionList;    
    114.     }    
    115.     public void setPermissionList(List<Permission> permissionList) {    
    116.         this.permissionList = permissionList;    
    117.     }    
    118.     @ManyToMany    
    119.     @JoinTable(name="t_user_role",joinColumns={@JoinColumn(name="role_id")},inverseJoinColumns={@JoinColumn(name="user_id")})    
    120.     public List<User> getUserList() {    
    121.         return userList;    
    122.     }    
    123.     public void setUserList(List<User> userList) {    
    124.         this.userList = userList;    
    125.     }    
    126.         
    127.     @Transient    
    128.     public List<String> getPermissionsName(){    
    129.         List<String> list=new ArrayList<String>();    
    130.         List<Permission> perlist=getPermissionList();    
    131.         for (Permission per : perlist) {    
    132.             list.add(per.getPermissionname());    
    133.         }    
    134.         return list;    
    135.     }    
    136. }    
    137.    
    138. Java代码  收藏代码  
    139. package com.cn.pojo;    
    140.     
    141. import javax.persistence.Entity;    
    142. import javax.persistence.GeneratedValue;    
    143. import javax.persistence.GenerationType;    
    144. import javax.persistence.Id;    
    145. import javax.persistence.JoinColumn;    
    146. import javax.persistence.ManyToOne;    
    147. import javax.persistence.Table;    
    148.     
    149. @Entity    
    150. @Table(name="t_permission")    
    151. public class Permission {    
    152.     
    153.     private Integer id;    
    154.     private String permissionname;    
    155.     private Role role;//一个权限对应一个角色    
    156.         
    157.     @Id    
    158.     @GeneratedValue(strategy=GenerationType.IDENTITY)    
    159.     public Integer getId() {    
    160.         return id;    
    161.     }    
    162.     public void setId(Integer id) {    
    163.         this.id = id;    
    164.     }    
    165.     public String getPermissionname() {    
    166.         return permissionname;    
    167.     }    
    168.     public void setPermissionname(String permissionname) {    
    169.         this.permissionname = permissionname;    
    170.     }    
    171.     @ManyToOne    
    172.     @JoinColumn(name="role_id")    
    173.     public Role getRole() {    
    174.         return role;    
    175.     }    
    176.     public void setRole(Role role) {    
    177.         this.role = role;    
    178.     }    
    179.         
    180. }    
    181.    
    182.  使用SHIRO的步骤:  
    183. 1,导入jar  
    184. 2,配置web.xml  
    185. 3,建立dbRelm  
    186. 4,在Spring中配置  
    187.   
    188. pom.xml中配置如下:  
    189. Xml代码  收藏代码  
    190. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    
    191.   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">    
    192.   <modelVersion>4.0.0</modelVersion>    
    193.   <groupId>com.hyx</groupId>    
    194.   <artifactId>springmvc</artifactId>    
    195.   <packaging>war</packaging>    
    196.   <version>0.0.1-SNAPSHOT</version>    
    197.   <name>springmvc Maven Webapp</name>    
    198.   <url>http://maven.apache.org</url>    
    199.   <dependencies>    
    200.     <dependency>    
    201.       <groupId>junit</groupId>    
    202.       <artifactId>junit</artifactId>    
    203.       <version>3.8.1</version>    
    204.       <scope>test</scope>    
    205.     </dependency>    
    206.     <!-- SpringMVC核心jar -->    
    207.     <dependency>    
    208.         <groupId>org.springframework</groupId>    
    209.         <artifactId>spring-webmvc</artifactId>    
    210.         <version>3.2.4.RELEASE</version>    
    211.     </dependency>    
    212.     <!-- springmvc连接数据库需要的jar -->    
    213.     <dependency>    
    214.         <groupId>org.springframework</groupId>    
    215.         <artifactId>spring-jdbc</artifactId>    
    216.         <version>3.2.4.RELEASE</version>    
    217.     </dependency>    
    218.     <dependency>    
    219.         <groupId>org.springframework</groupId>    
    220.         <artifactId>spring-orm</artifactId>    
    221.         <version>3.2.4.RELEASE</version>    
    222.     </dependency>    
    223.     <!-- ************************************ -->    
    224.     <!-- Hibernate相关jar -->    
    225.     <dependency>    
    226.         <groupId>org.hibernate</groupId>    
    227.         <artifactId>hibernate-core</artifactId>    
    228.         <version>4.2.5.Final</version>    
    229.     </dependency>    
    230.     <dependency>    
    231.         <groupId>org.hibernate</groupId>    
    232.         <artifactId>hibernate-ehcache</artifactId>    
    233.         <version>4.2.5.Final</version>    
    234.     </dependency>    
    235.     <dependency>    
    236.         <groupId>net.sf.ehcache</groupId>    
    237.         <artifactId>ehcache</artifactId>    
    238.         <version>2.7.2</version>    
    239.     </dependency>    
    240.     <dependency>    
    241.         <groupId>commons-dbcp</groupId>    
    242.         <artifactId>commons-dbcp</artifactId>    
    243.         <version>1.4</version>    
    244.     </dependency>    
    245.     <dependency>    
    246.         <groupId>mysql</groupId>    
    247.         <artifactId>mysql-connector-java</artifactId>    
    248.         <version>5.1.26</version>    
    249.     </dependency>    
    250.     <!-- javax提供的annotation -->    
    251.     <dependency>    
    252.         <groupId>javax.inject</groupId>    
    253.         <artifactId>javax.inject</artifactId>    
    254.         <version>1</version>    
    255.     </dependency>            
    256.     <!-- **************************** -->    
    257.         
    258.     <!-- hibernate验证 -->    
    259.     <dependency>    
    260.         <groupId>org.hibernate</groupId>    
    261.         <artifactId>hibernate-validator</artifactId>    
    262.         <version>5.0.1.Final</version>    
    263.     </dependency>    
    264.     <!-- 用于对@ResponseBody注解的支持 -->    
    265.     <dependency>    
    266.         <groupId>org.codehaus.jackson</groupId>    
    267.         <artifactId>jackson-mapper-asl</artifactId>    
    268.         <version>1.9.13</version>    
    269.     </dependency>            
    270.     <!-- 提供对c标签的支持 -->    
    271.     <dependency>    
    272.         <groupId>javax.servlet</groupId>    
    273.         <artifactId>jstl</artifactId>    
    274.         <version>1.2</version>    
    275.     </dependency>    
    276.     <!-- servlet api -->    
    277.     <dependency>    
    278.       <groupId>javax.servlet</groupId>    
    279.       <artifactId>servlet-api</artifactId>    
    280.       <version>2.5</version>    
    281.     </dependency>    
    282.         
    283.     <!--Apache Shiro所需的jar包-->      
    284.     <dependency>      
    285.       <groupId>org.apache.shiro</groupId>      
    286.       <artifactId>shiro-core</artifactId>      
    287.       <version>1.2.2</version>      
    288.     </dependency>      
    289.     <dependency>      
    290.       <groupId>org.apache.shiro</groupId>      
    291.       <artifactId>shiro-web</artifactId>      
    292.       <version>1.2.2</version>      
    293.     </dependency>      
    294.     <dependency>      
    295.       <groupId>org.apache.shiro</groupId>      
    296.       <artifactId>shiro-spring</artifactId>      
    297.       <version>1.2.2</version>      
    298.     </dependency>     
    299.   </dependencies>    
    300.       
    301.   <build>    
    302.     <finalName>springmvc</finalName>    
    303.     <!-- maven的jetty服务器插件 -->    
    304.     <plugins>    
    305.         <plugin>    
    306.           <groupId>org.mortbay.jetty</groupId>    
    307.           <artifactId>jetty-maven-plugin</artifactId>    
    308.           <configuration>    
    309.             <scanIntervalSeconds>10</scanIntervalSeconds>    
    310.             <webApp>    
    311.               <contextPath>/</contextPath>    
    312.             </webApp>    
    313.             <!-- 修改jetty的默认端口 -->    
    314.             <connectors>    
    315.                <connector implementation="org.eclipse.jetty.server.nio.SelectChannelConnector">    
    316.                   <port>80</port>    
    317.                   <maxIdleTime>60000</maxIdleTime>    
    318.                </connector>    
    319.             </connectors>    
    320.           </configuration>    
    321.         </plugin>    
    322.     </plugins>    
    323.   </build>    
    324. </project>    
    325.    
    326.  web.xml中的配置:  
    327. Xml代码  收藏代码  
    328. <?xml version="1.0" encoding="UTF-8" ?>    
    329. <web-app version="2.5"     
    330.     xmlns="http://java.sun.com/xml/ns/javaee"     
    331.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"     
    332.     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee     
    333.     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">    
    334.   <display-name>Archetype Created Web Application</display-name>    
    335.       
    336.   <!-- spring-orm-hibernate4的OpenSessionInViewFilter -->    
    337.   <filter>    
    338.     <filter-name>opensessioninview</filter-name>    
    339.     <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>    
    340.   </filter>    
    341.   <filter-mapping>    
    342.     <filter-name>opensessioninview</filter-name>    
    343.     <url-pattern>/*</url-pattern>   
    344.   </filter-mapping>   
    345.      
    346.   <!-- 配置springmvc servlet -->   
    347.   <servlet>   
    348.     <servlet-name>springmvc</servlet-name>   
    349.     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>   
    350.     <load-on-startup>1</load-on-startup>   
    351.   </servlet>   
    352.   <servlet-mapping>   
    353.     <servlet-name>springmvc</servlet-name>   
    354.     <!-- / 表示所有的请求都要经过此serlvet -->   
    355.     <url-pattern>/</url-pattern>   
    356.   </servlet-mapping>   
    357.      
    358.   <!-- spring的监听器 -->   
    359.   <context-param>   
    360.     <param-name>contextConfigLocation</param-name>   
    361.     <param-value>classpath:applicationContext*.xml</param-value>   
    362.   </context-param>   
    363.   <listener>   
    364.     <listener-class>   
    365.         org.springframework.web.context.ContextLoaderListener   
    366.     </listener-class>   
    367.   </listener>   
    368.      
    369.   <!-- Shiro配置 -->     
    370.   <filter>     
    371.     <filter-name>shiroFilter</filter-name>     
    372.     <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>     
    373.   </filter>     
    374.   <filter-mapping>     
    375.     <filter-name>shiroFilter</filter-name>     
    376.     <url-pattern>/*</url-pattern>     
    377.   </filter-mapping>   
    378.      
    379. </web-app>   
    380.   
    381.   
    382. Java代码  收藏代码 
    383. package com.cn.service;   
    384.    
    385. import java.util.List;   
    386.    
    387. import javax.inject.Inject;   
    388.    
    389. import org.apache.shiro.authc.AuthenticationException;   
    390. import org.apache.shiro.authc.AuthenticationInfo;   
    391. import org.apache.shiro.authc.AuthenticationToken;   
    392. import org.apache.shiro.authc.SimpleAuthenticationInfo;   
    393. import org.apache.shiro.authc.UsernamePasswordToken;   
    394. import org.apache.shiro.authz.AuthorizationInfo;   
    395. import org.apache.shiro.authz.SimpleAuthorizationInfo;   
    396. import org.apache.shiro.realm.AuthorizingRealm;   
    397. import org.apache.shiro.subject.PrincipalCollection;   
    398. import org.springframework.stereotype.Service;   
    399. import org.springframework.transaction.annotation.Transactional;   
    400.    
    401. import com.cn.pojo.Role;   
    402. import com.cn.pojo.User;   
    403.    
    404. @Service   
    405. @Transactional   
    406. public class MyShiro extends AuthorizingRealm{   
    407.    
    408.     @Inject   
    409.     private UserService userService;   
    410.     /**  
    411.      * 权限认证  
    412.      */    
    413.     @Override    
    414.     protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {    
    415.         //获取登录时输入的用户名    
    416.         String loginName=(String) principalCollection.fromRealm(getName()).iterator().next();    
    417.         //到数据库查是否有此对象    
    418.         User user=userService.findByName(loginName);    
    419.         if(user!=null){    
    420.             //权限信息对象info,用来存放查出的用户的所有的角色(role)及权限(permission)    
    421.             SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();    
    422.             //用户的角色集合    
    423.             info.setRoles(user.getRolesName());    
    424.             //用户的角色对应的所有权限,如果只使用角色定义访问权限,下面的四行可以不要    
    425.             List<Role> roleList=user.getRoleList();    
    426.             for (Role role : roleList) {    
    427.                 info.addStringPermissions(role.getPermissionsName());    
    428.             }    
    429.             return info;    
    430.         }    
    431.         return null;    
    432.     }    
    433.     
    434.     /**  
    435.      * 登录认证;  
    436.      */    
    437.     @Override    
    438.     protected AuthenticationInfo doGetAuthenticationInfo(    
    439.             AuthenticationToken authenticationToken) throws AuthenticationException {    
    440.         //UsernamePasswordToken对象用来存放提交的登录信息    
    441.         UsernamePasswordToken token=(UsernamePasswordToken) authenticationToken;    
    442.         //查出是否有此用户    
    443.         User user=userService.findByName(token.getUsername());    
    444.         if(user!=null){    
    445.             //若存在,将此用户存放到登录认证info中    
    446.             return new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), getName());    
    447.         }    
    448.         return null;    
    449.     }    
    450.     
    451. }    


 

 在spring的配置文件中配置,为了区别spring原配置和shiro我们将shiro的配置独立出来。

applicationContext-shiro.xml

[java]  view plain  copy
  1. <?xml version="1.0" encoding="UTF-8" ?>    
  2. <beans xmlns="http://www.springframework.org/schema/beans"    
  3.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    
  4.        xmlns:aop="http://www.springframework.org/schema/aop"    
  5.        xmlns:tx="http://www.springframework.org/schema/tx"    
  6.        xmlns:context="http://www.springframework.org/schema/context"    
  7.        xsi:schemaLocation="    
  8. http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd    
  9. http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd    
  10. http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd    
  11. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">    
  12.     
  13.     <!-- 配置权限管理器 -->    
  14.     <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">      
  15.         <!-- ref对应我们写的realm  MyShiro -->    
  16.         <property name="realm" ref="myShiro"/>      
  17.         <!-- 使用下面配置的缓存管理器 -->    
  18.         <property name="cacheManager" ref="cacheManager"/>      
  19.     </bean>    
  20.         
  21.     <!-- 配置shiro的过滤器工厂类,id- shiroFilter要和我们在web.xml中配置的过滤器一致 -->    
  22.     <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">     
  23.         <!-- 调用我们配置的权限管理器 -->     
  24.         <property name="securityManager" ref="securityManager"/>     
  25.         <!-- 配置我们的登录请求地址 -->     
  26.         <property name="loginUrl" value="/login"/>      
  27.         <!-- 配置我们在登录页登录成功后的跳转地址,如果你访问的是非/login地址,则跳到您访问的地址 -->    
  28.         <property name="successUrl" value="/user"/>      
  29.         <!-- 如果您请求的资源不再您的权限范围,则跳转到/403请求地址 -->    
  30.         <property name="unauthorizedUrl" value="/403"/>      
  31.         <!-- 权限配置 -->    
  32.         <property name="filterChainDefinitions">      
  33.             <value>      
  34.                 <!-- anon表示此地址不需要任何权限即可访问 -->    
  35.                 /static/**=anon    
  36.                 <!-- perms[user:query]表示访问此连接需要权限为user:query的用户 -->    
  37.                 /user=perms[user:query]    
  38.                 <!-- roles[manager]表示访问此连接需要用户的角色为manager -->    
  39.                 /user/add=roles[manager]    
  40.                 /user/del/**=roles[admin]    
  41.                 /user/edit/**=roles[manager]    
  42.                 <!--所有的请求(除去配置的静态资源请求或请求地址为anon的请求)都要通过登录验证,如果未登录则跳到/login-->      
  43.                 /** = authc    
  44.             </value>      
  45.         </property>      
  46.     </bean>    
  47.         
  48.         
  49.     <bean id="cacheManager" class="org.apache.shiro.cache.MemoryConstrainedCacheManager" />      
  50.     <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />     
  51.         
  52. </beans>    

 用于登录,登出,权限跳转的控制:

Java代码   收藏代码
  1. [java]  view plain  copy
    1. package com.cn.controller;    
    2.     
    3. import javax.validation.Valid;    
    4.     
    5. import org.apache.shiro.SecurityUtils;    
    6. import org.apache.shiro.authc.AuthenticationException;    
    7. import org.apache.shiro.authc.UsernamePasswordToken;    
    8. import org.springframework.stereotype.Controller;    
    9. import org.springframework.ui.Model;    
    10. import org.springframework.validation.BindingResult;    
    11. import org.springframework.web.bind.annotation.RequestMapping;    
    12. import org.springframework.web.bind.annotation.RequestMethod;    
    13. import org.springframework.web.servlet.mvc.support.RedirectAttributes;    
    14.     
    15. import com.cn.pojo.User;    
    16.     
    17. @Controller    
    18. public class HomeController {    
    19.     
    20.     @RequestMapping(value="/login",method=RequestMethod.GET)    
    21.     public String loginForm(Model model){    
    22.         model.addAttribute("user"new User());    
    23.         return "/login";    
    24.     }    
    25.         
    26.     @RequestMapping(value="/login",method=RequestMethod.POST)    
    27.     public String login(@Valid User user,BindingResult bindingResult,RedirectAttributes redirectAttributes){    
    28.         try {    
    29.             if(bindingResult.hasErrors()){    
    30.                 return "/login";    
    31.             }    
    32.             //使用权限工具进行用户登录,登录成功后跳到shiro配置的successUrl中,与下面的return没什么关系!    
    33.             SecurityUtils.getSubject().login(new UsernamePasswordToken(user.getUsername(), user.getPassword()));    
    34.             return "redirect:/user";    
    35.         } catch (AuthenticationException e) {    
    36.             redirectAttributes.addFlashAttribute("message","用户名或密码错误");    
    37.             return "redirect:/login";    
    38.         }    
    39.     }    
    40.         
    41.     @RequestMapping(value="/logout",method=RequestMethod.GET)      
    42.     public String logout(RedirectAttributes redirectAttributes ){     
    43.         //使用权限管理工具进行用户的退出,跳出登录,给出提示信息    
    44.         SecurityUtils.getSubject().logout();      
    45.         redirectAttributes.addFlashAttribute("message""您已安全退出");      
    46.         return "redirect:/login";    
    47.     }     
    48.         
    49.     @RequestMapping("/403")    
    50.     public String unauthorizedRole(){    
    51.         return "/403";    
    52.     }    
    53. }    


 

 三个主要的JSP:
login.jsp:

Html代码   收藏代码
  1. [java]  view plain  copy
    1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>    
    2. <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>    
    3. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">    
    4. <html>    
    5.   <head>    
    6.     <title>My JSP 'MyJsp.jsp' starting page</title>    
    7.   </head>    
    8.       
    9.   <body>    
    10.     <h1>登录页面----${message }</h1>    
    11.     <img alt="" src="/static/img/1.jpg">    
    12.     <form:form action="/login" commandName="user" method="post">    
    13.         用户名:<form:input path="username"/> <form:errors path="username" cssClass="error"/> <br/>    
    14.         密   码:<form:password path="password"/> <form:errors path="password" cssClass="error" /> <br/>    
    15.         <form:button name="button">submit</form:button>    
    16.     </form:form>    
    17.   </body>    
    18. </html>    
    19.    


 user.jsp:

Html代码   收藏代码
  1. [java]  view plain  copy
    1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>    
    2. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>    
    3. <%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>    
    4. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">    
    5. <html>    
    6.   <head>    
    7.     <title>用户列表</title>    
    8.   </head>    
    9.   <body>    
    10.     <h1>${message }</h1>    
    11.     <h1>用户列表--<a href="/user/add">添加用户</a>---<a href="/logout">退出登录</a>    </h1>    
    12.     <h2>权限列表</h2>    
    13.     <shiro:authenticated>用户已经登录显示此内容</shiro:authenticated>    
    14.     <shiro:hasRole name="manager">manager角色登录显示此内容</shiro:hasRole>    
    15.     <shiro:hasRole name="admin">admin角色登录显示此内容</shiro:hasRole>    
    16.     <shiro:hasRole name="normal">normal角色登录显示此内容</shiro:hasRole>    
    17.         
    18.     <shiro:hasAnyRoles name="manager,admin">**manager or admin 角色用户登录显示此内容**</shiro:hasAnyRoles>    
    19.     <shiro:principal/>-显示当前登录用户名    
    20.     <shiro:hasPermission name="add">add权限用户显示此内容</shiro:hasPermission>    
    21.     <shiro:hasPermission name="user:query">query权限用户显示此内容<shiro:principal/></shiro:hasPermission>    
    22.     <shiro:lacksPermission name="user:del"> 不具有user:del权限的用户显示此内容 </shiro:lacksPermission>    
    23.     <ul>    
    24.         <c:forEach items="${userList }" var="user">    
    25.             <li>用户名:${user.username }----密码:${user.password }----<a href="/user/edit/${user.id}">修改用户</a>----<a href="javascript:;" class="del" ref="${user.id }">删除用户</a></li>    
    26.         </c:forEach>    
    27.     </ul>    
    28.     <img alt="" src="/static/img/1.jpg">    
    29.     <script type="text/javascript" src="http://cdn.staticfile.org/jquery/1.9.1/jquery.min.js"></script>    
    30.     <script>    
    31.         $(function(){    
    32.             $(".del").click(function(){    
    33.                 var id=$(this).attr("ref");    
    34.                 $.ajax({    
    35.                     type:"delete",    
    36.                     url:"/user/del/"+id,    
    37.                     success:function(e){    
    38.                             
    39.                     }    
    40.                 });    
    41.             });    
    42.         });    
    43.     </script>    
    44.   </body>    
    45. </html>    


 

 

 403.jsp:

Html代码   收藏代码
  1. [java]  view plain  copy
    1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>    
    2. <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>    
    3. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">    
    4. <html>    
    5.   <head>    
    6.     <title>权限错误</title>    
    7.   </head>    
    8.       
    9.   <body>    
    10.     <h1>对不起,您没有权限请求此连接!</h1>    
    11.     <img alt="" src="/static/img/1.jpg">    
    12.         
    13.   </body>    
    14. </html>    


本文转自:http://www.360doc.com/content/14/0529/10/11298474_381933566.shtml

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值