将Shiro整到SSM中(基于maven)

简介

1.shiro是用于权限控制还有对密码加密的框架,同时可以控制尝试登入次数,超出将对用户锁定

2.shiro的运行轨迹是用户登入以后,shiro会自动查询用户的角色以及权限,并将用户信息保存到session里,当用户在进行访问资源时候,会根据之前对资源权限的定义,检查用户是否具有这个权限,比如访问/allUser,访问需要admin的角色,shiro会根据登入用户的信息,检查用户是否具有admin的角色

3.shiro1.2提供了passwordService,对密码加密更加方便

4.shiro的shiroFilter配置,如果是访问其他已存在的页面被拦截到登录页面,登录后就会跳转到之前的页面;如果是直接访问登录页面或者是通过退出登录到登录页面,再次登录就会跳转到“/”

5.Spring MVC的json传输,可以自动的根据属性名称,将json和对象自动转换

6.实例环境的搭建 http://blog.csdn.net/zzhao114/article/details/54958339

7.实例用到的mybatis多表联立 http://blog.csdn.net/zzhao114/article/details/55106270

8.实例  http://download.csdn.net/download/zzhao114/9757441

(http://download.csdn.net/download/zzhao114/9936992  这个加入了数据库还有简单的文档)


将Shiro整到SSM中(基于maven)

--------------------------------------------------------------------------------------------------------------------

    Shiro整到Spring中后,我们自定义的realm啊、securityManager等都会交给spring去管理了,包括我们需要指定哪些url需要做什么样的验证,都是交给spring,也就是说,完全可以摆脱原来的那个.ini配置文件了,Shiro部分参考了它的官方文档:http://shiro.apache.org/spring.html

1.

将Shiro整到SSM中(基于maven)_第1张图片

2.配置文件

2.1 pom.xml

[html] view plain copy
  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  2.   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">  
  3.   <modelVersion>4.0.0modelVersion>  
  4.   <groupId>com.demogroupId>  
  5.   <artifactId>shiroartifactId>  
  6.   <packaging>warpackaging>  
  7.   <version>1.0-SNAPSHOTversion>  
  8.   <name>shiro Maven Webappname>  
  9.   <url>http://maven.apache.orgurl>  
  10.   <dependencies>  
  11.       
  12.     <dependency>  
  13.       <groupId>org.apache.shirogroupId>  
  14.       <artifactId>shiro-coreartifactId>  
  15.       <version>1.2.5version>  
  16.     dependency>  
  17.       
  18.     <dependency>  
  19.       <groupId>org.apache.shirogroupId>  
  20.       <artifactId>shiro-webartifactId>  
  21.       <version>1.2.5version>  
  22.     dependency>  
  23.       
  24.     <dependency>  
  25.       <groupId>org.apache.shirogroupId>  
  26.       <artifactId>shiro-springartifactId>  
  27.       <version>1.2.5version>  
  28.     dependency>  
  29.       
  30.     <dependency>  
  31.       <groupId>javax.servletgroupId>  
  32.       <artifactId>javax.servlet-apiartifactId>  
  33.       <version>3.1.0version>  
  34.     dependency>  
  35.       
  36.     <dependency>  
  37.       <groupId>javax.servlet.jspgroupId>  
  38.       <artifactId>javax.servlet.jsp-apiartifactId>  
  39.       <version>2.3.1version>  
  40.     dependency>  
  41.       
  42.     <dependency>  
  43.       <groupId>javax.servletgroupId>  
  44.       <artifactId>jstlartifactId>  
  45.       <version>1.2version>  
  46.     dependency>  
  47.       
  48.     <dependency>  
  49.       <groupId>log4jgroupId>  
  50.       <artifactId>log4jartifactId>  
  51.       <version>1.2.17version>  
  52.     dependency>  
  53.     <dependency>  
  54.       <groupId>commons-logginggroupId>  
  55.       <artifactId>commons-loggingartifactId>  
  56.       <version>1.2version>  
  57.     dependency>  
  58.     <dependency>  
  59.       <groupId>org.slf4jgroupId>  
  60.       <artifactId>slf4j-apiartifactId>  
  61.       <version>1.7.21version>  
  62.     dependency>  
  63.   
  64.       
  65.     <dependency>  
  66.       <groupId>org.springframeworkgroupId>  
  67.       <artifactId>spring-coreartifactId>  
  68.       <version>4.3.0.RELEASEversion>  
  69.     dependency>  
  70.     <dependency>  
  71.       <groupId>org.springframeworkgroupId>  
  72.       <artifactId>spring-beansartifactId>  
  73.       <version>4.3.0.RELEASEversion>  
  74.     dependency>  
  75.     <dependency>  
  76.       <groupId>org.springframeworkgroupId>  
  77.       <artifactId>spring-contextartifactId>  
  78.       <version>4.3.0.RELEASEversion>  
  79.     dependency>  
  80.     <dependency>  
  81.       <groupId>org.springframeworkgroupId>  
  82.       <artifactId>spring-context-supportartifactId>  
  83.       <version>4.3.0.RELEASEversion>  
  84.     dependency>  
  85.     <dependency>  
  86.       <groupId>org.springframeworkgroupId>  
  87.       <artifactId>spring-webartifactId>  
  88.       <version>4.3.0.RELEASEversion>  
  89.     dependency>  
  90.     <dependency>  
  91.       <groupId>org.springframeworkgroupId>  
  92.       <artifactId>spring-webmvcartifactId>  
  93.       <version>4.3.0.RELEASEversion>  
  94.     dependency>  
  95.     <dependency>  
  96.       <groupId>org.springframeworkgroupId>  
  97.       <artifactId>spring-txartifactId>  
  98.       <version>4.3.0.RELEASEversion>  
  99.     dependency>  
  100.     <dependency>  
  101.       <groupId>org.springframeworkgroupId>  
  102.       <artifactId>spring-jdbcartifactId>  
  103.       <version>4.3.0.RELEASEversion>  
  104.     dependency>  
  105.     <dependency>  
  106.       <groupId>org.springframeworkgroupId>  
  107.       <artifactId>spring-aopartifactId>  
  108.       <version>4.3.0.RELEASEversion>  
  109.     dependency>  
  110.     <dependency>  
  111.       <groupId>org.springframeworkgroupId>  
  112.       <artifactId>spring-aspectsartifactId>  
  113.       <version>4.3.0.RELEASEversion>  
  114.     dependency>  
  115.   
  116.       
  117.     <dependency>  
  118.       <groupId>org.mybatisgroupId>  
  119.       <artifactId>mybatisartifactId>  
  120.       <version>3.4.0version>  
  121.     dependency>  
  122.     <dependency>  
  123.       <groupId>org.mybatisgroupId>  
  124.       <artifactId>mybatis-springartifactId>  
  125.       <version>1.3.0version>  
  126.     dependency>  
  127.   
  128.     <dependency>  
  129.       <groupId>com.oraclegroupId>  
  130.       <artifactId>ojdbc14artifactId>  
  131.       <version>11.1.0.6.0version>  
  132.     dependency>  
  133.   
  134.     <dependency>  
  135.       <groupId>junitgroupId>  
  136.       <artifactId>junitartifactId>  
  137.       <version>4.12version>  
  138.       <scope>testscope>  
  139.     dependency>  
  140.   dependencies>  
  141.   <build>  
  142.     <finalName>shirofinalName>  
  143.   build>  
  144. project>  
  145. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  146.   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">  
  147.   <modelVersion>4.0.0modelVersion>  
  148.   <groupId>com.demogroupId>  
  149.   <artifactId>shiroartifactId>  
  150.   <packaging>warpackaging>  
  151.   <version>1.0-SNAPSHOTversion>  
  152.   <name>shiro Maven Webappname>  
  153.   <url>http://maven.apache.orgurl>  
  154.   <dependencies>  
  155.       
  156.     <dependency>  
  157.       <groupId>org.apache.shirogroupId>  
  158.       <artifactId>shiro-coreartifactId>  
  159.       <version>1.2.5version>  
  160.     dependency>  
  161.       
  162.     <dependency>  
  163.       <groupId>org.apache.shirogroupId>  
  164.       <artifactId>shiro-webartifactId>  
  165.       <version>1.2.5version>  
  166.     dependency>  
  167.       
  168.     <dependency>  
  169.       <groupId>org.apache.shirogroupId>  
  170.       <artifactId>shiro-springartifactId>  
  171.       <version>1.2.5version>  
  172.     dependency>  
  173.       
  174.     <dependency>  
  175.       <groupId>javax.servletgroupId>  
  176.       <artifactId>javax.servlet-apiartifactId>  
  177.       <version>3.1.0version>  
  178.     dependency>  
  179.       
  180.     <dependency>  
  181.       <groupId>javax.servlet.jspgroupId>  
  182.       <artifactId>javax.servlet.jsp-apiartifactId>  
  183.       <version>2.3.1version>  
  184.     dependency>  
  185.       
  186.     <dependency>  
  187.       <groupId>javax.servletgroupId>  
  188.       <artifactId>jstlartifactId>  
  189.       <version>1.2version>  
  190.     dependency>  
  191.       
  192.     <dependency>  
  193.       <groupId>log4jgroupId>  
  194.       <artifactId>log4jartifactId>  
  195.       <version>1.2.17version>  
  196.     dependency>  
  197.     <dependency>  
  198.       <groupId>commons-logginggroupId>  
  199.       <artifactId>commons-loggingartifactId>  
  200.       <version>1.2version>  
  201.     dependency>  
  202.     <dependency>  
  203.       <groupId>org.slf4jgroupId>  
  204.       <artifactId>slf4j-apiartifactId>  
  205.       <version>1.7.21version>  
  206.     dependency>  
  207.   
  208.       
  209.     <dependency>  
  210.       <groupId>org.springframeworkgroupId>  
  211.       <artifactId>spring-coreartifactId>  
  212.       <version>4.3.0.RELEASEversion>  
  213.     dependency>  
  214.     <dependency>  
  215.       <groupId>org.springframeworkgroupId>  
  216.       <artifactId>spring-beansartifactId>  
  217.       <version>4.3.0.RELEASEversion>  
  218.     dependency>  
  219.     <dependency>  
  220.       <groupId>org.springframeworkgroupId>  
  221.       <artifactId>spring-contextartifactId>  
  222.       <version>4.3.0.RELEASEversion>  
  223.     dependency>  
  224.     <dependency>  
  225.       <groupId>org.springframeworkgroupId>  
  226.       <artifactId>spring-context-supportartifactId>  
  227.       <version>4.3.0.RELEASEversion>  
  228.     dependency>  
  229.     <dependency>  
  230.       <groupId>org.springframeworkgroupId>  
  231.       <artifactId>spring-webartifactId>  
  232.       <version>4.3.0.RELEASEversion>  
  233.     dependency>  
  234.     <dependency>  
  235.       <groupId>org.springframeworkgroupId>  
  236.       <artifactId>spring-webmvcartifactId>  
  237.       <version>4.3.0.RELEASEversion>  
  238.     dependency>  
  239.     <dependency>  
  240.       <groupId>org.springframeworkgroupId>  
  241.       <artifactId>spring-txartifactId>  
  242.       <version>4.3.0.RELEASEversion>  
  243.     dependency>  
  244.     <dependency>  
  245.       <groupId>org.springframeworkgroupId>  
  246.       <artifactId>spring-jdbcartifactId>  
  247.       <version>4.3.0.RELEASEversion>  
  248.     dependency>  
  249.     <dependency>  
  250.       <groupId>org.springframeworkgroupId>  
  251.       <artifactId>spring-aopartifactId>  
  252.       <version>4.3.0.RELEASEversion>  
  253.     dependency>  
  254.     <dependency>  
  255.       <groupId>org.springframeworkgroupId>  
  256.       <artifactId>spring-aspectsartifactId>  
  257.       <version>4.3.0.RELEASEversion>  
  258.     dependency>  
  259.   
  260.       
  261.     <dependency>  
  262.       <groupId>org.mybatisgroupId>  
  263.       <artifactId>mybatisartifactId>  
  264.       <version>3.4.0version>  
  265.     dependency>  
  266.     <dependency>  
  267.       <groupId>org.mybatisgroupId>  
  268.       <artifactId>mybatis-springartifactId>  
  269.       <version>1.3.0version>  
  270.     dependency>  
  271.   
  272.     <dependency>  
  273.       <groupId>com.oraclegroupId>  
  274.       <artifactId>ojdbc14artifactId>  
  275.       <version>11.1.0.6.0version>  
  276.     dependency>  
  277.   
  278.     <dependency>  
  279.       <groupId>junitgroupId>  
  280.       <artifactId>junitartifactId>  
  281.       <version>4.12version>  
  282.       <scope>testscope>  
  283.     dependency>  
  284.   dependencies>  
  285.   <build>  
  286.     <finalName>shirofinalName>  
  287.   build>  
  288. project>  
2.2 log4j.properties
[java] view plain copy
  1. log4j.rootLogger=DEBUG, Console    
  2.   
  3. #Console    
  4. log4j.appender.Console=org.apache.log4j.ConsoleAppender    
  5. log4j.appender.Console.layout=org.apache.log4j.PatternLayout    
  6. log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n    
  7.   
  8. log4j.logger.java.sql.ResultSet=INFO    
  9. log4j.logger.org.apache=INFO    
  10. log4j.logger.java.sql.Connection=DEBUG    
  11. log4j.logger.java.sql.Statement=DEBUG    
  12. log4j.logger.java.sql.PreparedStatement=DEBUG    

2.3 web.xml(有待修改)

[html] view plain copy
  1. xml version="1.0" encoding="UTF-8"?>  
  2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">  
  3.   <display-name>ShiroSpringdisplay-name>  
  4.   <welcome-file-list>  
  5.     <welcome-file>index.jspwelcome-file>  
  6.   welcome-file-list>  
  7.   
  8.     
  9.   <listener>  
  10.     <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>  
  11.   listener>  
  12.   <context-param>  
  13.     <param-name>contextConfigLocationparam-name>  
  14.     <param-value>classpath:applicationContext.xmlparam-value>  
  15.   context-param>  
  16.   
  17.     
  18.   <servlet>  
  19.     <servlet-name>springMVCservlet-name>  
  20.     <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>  
  21.     <init-param>  
  22.         <param-name>contextConfigLocationparam-name>  
  23.         <param-value>classpath:spring-mvc.xmlparam-value>  
  24.     init-param>  
  25.   servlet>  
  26.   <servlet-mapping>  
  27.     <servlet-name>springMVCservlet-name>  
  28.     <url-pattern>*.dourl-pattern>  
  29.   servlet-mapping>  
  30.   
  31.     
  32.   <filter>  
  33.     <filter-name>shiroFilterfilter-name>  
  34.     <filter-class>org.springframework.web.filter.DelegatingFilterProxyfilter-class>  
  35.     <init-param>  
  36.           
  37.         <param-name>targetFilterLifecycleparam-name>  
  38.         <param-value>trueparam-value>  
  39.     init-param>  
  40.   filter>  
  41.   <filter-mapping>  
  42.     <filter-name>shiroFilterfilter-name>  
  43.     <url-pattern>/*url-pattern>  
  44.   filter-mapping>  
  45.   
  46.     
  47.   <filter>  
  48.     <filter-name>encodingFilterfilter-name>  
  49.     <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>  
  50.     <async-supported>trueasync-supported>  
  51.     <init-param>  
  52.         <param-name>encodingparam-name>  
  53.         <param-value>UTF-8param-value>  
  54.     init-param>  
  55.   filter>  
  56.   <filter-mapping>  
  57.     <filter-name>encodingFilterfilter-name>  
  58.     <url-pattern>/*url-pattern>  
  59.   filter-mapping>  
  60. web-app>  
2.4  applicationContext.xml(核心配置)

[html] 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:p="http://www.springframework.org/schema/p"  
  5.        xmlns:aop="http://www.springframework.org/schema/aop"  
  6.        xmlns:context="http://www.springframework.org/schema/context"  
  7.        xmlns:jee="http://www.springframework.org/schema/jee"  
  8.        xmlns:tx="http://www.springframework.org/schema/tx"  
  9.        xsi:schemaLocation=" http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd  
  10.         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd  
  11.         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd  
  12.         http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd  
  13.         http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">  
  14.   
  15.       
  16.     <context:component-scan base-package="demo.service" />  
  17.   
  18.       
  19.     <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
  20.         <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>  
  21.         <property name="url" value="jdbc:oracle:thin:@192.168.6.34:1521:orcl"/>  
  22.         <property name="username" value="scott"/>  
  23.         <property name="password" value="tiger"/>  
  24.     bean>  
  25.   
  26.       
  27.     <bean name="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
  28.         <property name="dataSource" ref="dataSource"/>  
  29.           
  30.         <property name="mapperLocations" value="classpath:demo/mappers/*.xml "/>  
  31.           
  32.         <property name="configLocation" value="classpath:mybatis-config.xml"/>  
  33.     bean>  
  34.   
  35.       
  36.     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
  37.         <property name="basePackage" value="demo.dao"/>  
  38.         <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>  
  39.     bean>  
  40.   
  41.       
  42.     <bean id="myRealm" class="demo.realm.MyRealm"/>  
  43.   
  44.       
  45.     <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">  
  46.         <property name="realm" ref="myRealm">property>  
  47.     bean>  
  48.   
  49.       
  50.     <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">  
  51.           
  52.         <property name="securityManager" ref="securityManager"/>  
  53.           
  54.         <property name="loginUrl" value="/login.jsp"/>  
  55.           
  56.         <property name="unauthorizedUrl" value="/unauthorized.jsp"/>  
  57.           
  58.         <property name="filterChainDefinitions">  
  59.             <value>  
  60.                 /login=anon  
  61.                 /user/admin*=autho  
  62.                 /user/student*/**=roles[teacher]  
  63.                 /user/teacher*/**=perms["user:create"]  
  64.             value>  
  65.         property>  
  66.     bean>  
  67. beans>  

3.整合Mybatis

3.1全局配置文件

    首先配置一个mybatis的全局配置文件mybatis-config.xml,因为数据源都交给spring管理了,所以全局配置文件就比较清晰了。

   mybatis-config.xml

[html] view plain copy
  1. xml version="1.0" encoding="UTF-8" ?>  
  2.         PUBLIC "-//mybatis.org//DTD Config 3.0//EN"  
  3.         "http://mybatis.org/dtd/mybatis-3-config.dtd">  
  4. <configuration>  
  5.       
  6.     <typeAliases>  
  7.         <package name="demo.entity"/>  
  8.     typeAliases>  
  9. configuration>  
3.2配置mapper映射文件

    UserMapper.xml

[html] view plain copy
  1. xml version="1.0" encoding="UTF-8" ?>  
  2.         PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"  
  3.         "http://mybatis.org/dtd/mybatis-3-mapper.dtd">  
  4. <mapper>  
  5.     <select id="getByUsername" parameterType="String" resultType="user">  
  6.         select * from tb_user where username=#{username}  
  7.     select>  
  8.   
  9.     <select id="getRoles" parameterType="String" resultType="String">  
  10.         select r.rolename  from t_user u,t_role r where u.role_id=r.id and u.username=#{username}  
  11.     select>  
  12.   
  13.     <select id="getPermissions" parameterType="String" resultType="String">  
  14.         select p.permissionname from t_user u,t_role r,t_permission p where u.role_id=r.id and p.role_id=r.id  
  15.         and u.username=#{username}  
  16.     select>  
  17. mapper>  
3.3mapper接口(UserDao)

[java] view plain copy
  1. public interface UserDao {  
  2.     public User getByUsername(String username);  
  3.   
  4.     public Set getRoles(String username);  
  5.   
  6.     public Set getPermissions(String username);  
  7.   
  8. }  
    只需要写接口,不需要写实现,spring的配置文件中会去扫描mapper,会自动创建一个代理对象来执行相应的方法,要注意的是这个接口的方法名要和上面mapper映射文件的id号一样的,否则是无法映射到具体的statement上面的,会报错。


3.4 entity类

    这里写个简单的User类

[java] view plain copy
  1. public class User {  
  2.     private Integer  id;  
  3.     private String username;  
  4.     private String password;  
  5.     //get set方法省略  
  6.   
  7. }  
3.5  Service
    接口UserService.java

[java] view plain copy
  1. public interface UserService {  
  2.     public User getByUsername(String username);  
  3.   
  4.     public Set getRoles(String username);  
  5.   
  6.     public Set getPermissions(String username);  
  7.   
  8. }  

    UserServiceImpl.java

[java] view plain copy
  1. @Service("userService")  
  2. public class UserServiceImpl implements UserService {  
  3.     @Resource  
  4.     private UserDao userDao;  
  5.     public User getByUsername(String username){  
  6.             return userDao.getByUsername(username);  
  7.     }  
  8.     public Set getRoles(String username){  
  9.             return userDao.getRoles(username);  
  10.     }  
  11.     public Set getPermissions(String username){  
  12.            return userDao.getPermissions(username);  
  13.     }  
  14. }  
在service的实现类中,注入刚刚写好的dao接口即可调用其中的方法了,使用的是spring自动创建的代理对象去执行的。

4 整合SpringMVC

4.1配置文件

spring-mvc.xml

[html] 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:p="http://www.springframework.org/schema/p"  
  5.        xmlns:aop="http://www.springframework.org/schema/aop"  
  6.        xmlns:context="http://www.springframework.org/schema/context"  
  7.        xmlns:jee="http://www.springframework.org/schema/jee"  
  8.        xmlns:tx="http://www.springframework.org/schema/tx"  
  9.        xsi:schemaLocation="  
  10.         http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd  
  11.         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd  
  12.         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd  
  13.         http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd  
  14.         http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">  
  15.   
  16. <context:component-scan base-package="demo.controller"/>  
  17.   
  18.   
  19. <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
  20.     <property name="prefix" value="/">property>  
  21.     <property name="suffix" value=".jsp">property>  
  22. bean>  
  23. beans>  

4.2 Controller

    UserController.java

[java] view plain copy
  1. package demo.controller;  
  2.   
  3. import demo.entity.User;  
  4. import org.apache.shiro.SecurityUtils;  
  5. import org.apache.shiro.authc.UsernamePasswordToken;  
  6. import org.apache.shiro.subject.Subject;  
  7. import org.springframework.web.bind.annotation.RequestMapping;  
  8. import org.springframework.stereotype.Controller;  
  9. import javax.servlet.http.HttpServletRequest;  
  10.   
  11. @Controller  
  12. @RequestMapping("/user")  
  13. public class UserController {  
  14.     //用户登录  
  15.     @RequestMapping("/login")  
  16.     public String login(User user, HttpServletRequest request){  
  17.   
  18.         Subject subject=SecurityUtils.getSubject();  
  19.         UsernamePasswordToken token=new UsernamePasswordToken(user.getUsername(),user.getPassword());  
  20.         try {  
  21.             //调用subject.login(token)进行登录,会自动委托给securityManager,调用之前  
  22.             subject.login(token);//会跳到我们自定义的realm中  
  23.             request.getSession().setAttribute("user",user);  
  24.             return "success";  
  25.         }catch (Exception e){  
  26.             e.printStackTrace();  
  27.             request.getSession().setAttribute("user",user);  
  28.             request.setAttribute("error","用户名或密码错误");  
  29.             return "login";  
  30.         }  
  31.     }  
  32.   
  33.     @RequestMapping("/logout")  
  34.     public String logout(HttpServletRequest request){  
  35.         request.getSession().invalidate();  
  36.         return "index";  
  37.     }  
  38.   
  39.     @RequestMapping("/admin")  
  40.     public String admin(HttpServletRequest request){  
  41.         return "success";  
  42.     }  
  43.   
  44.     @RequestMapping("/student")  
  45.     public String student(HttpServletRequest request){  
  46.         return "success";  
  47.     }  
  48.   
  49.     @RequestMapping("/teacher")  
  50.     public String teacher(HttpServletRequest request){  
  51.         return "success";  
  52.     }  
  53. }  
4.3完成自定义的realm

    上面用户登录会执行一个subject.login(token);这里会跳转到我们自定义的realm中,接下来就定义一下我们自己的realm,由于这里是和mybatis整合了,所以不需要原来的那个Dbutil去连接数据库了,直接使用mybatis中的mapper接口,也就是上面写的dao。

[java] view plain copy
  1. public class MyRealm extends AuthorizingRealm {  
  2.     @Resource  
  3.     private UserServiceImpl userServiceImpl;  
  4.   
  5.     //为当前登录成功的用户授予权限和角色,已经登录成功了。  
  6.     protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {  
  7.         String username=(String) principals.getPrimaryPrincipal();  
  8.         SimpleAuthorizationInfo  authorizationInfo=new SimpleAuthorizationInfo();  
  9.         authorizationInfo.setRoles(userServiceImpl.getRoles(username));  
  10.         authorizationInfo.setStringPermissions(userServiceImpl.getPermissions(username));  
  11.         return authorizationInfo;  
  12.     }  
  13.     //验证当前登录的用户,获取认证信息。  
  14.     protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {  
  15.         String username=(String) token.getPrincipal();//获取用户名  
  16.         User user=userServiceImpl.getByUsername(username);  
  17.         if(user!=null){  
  18.             AuthenticationInfo authcInfo =new SimpleAuthenticationInfo(user.getUsername(),user.getPassword(),"myRealm");  
  19.             return authcInfo;  
  20.         }else{  
  21.             return null;  
  22.         }  
  23.     }  
  24. }  
5.几个jsp页面

login.jsp

[java] view plain copy
  1.   
  2.     "${pageContext.request.contextPath }/user/login.do" method="post">  
  3.         username:"text" name="username"/>
      
  4.         password:"password" name="password"/>
      
  5.         "submit" value="登录">${error}  
  6.       
  7.   

success.jsp

[java] view plain copy
  1.   
  2.     欢迎你${user.username}  
  3.     "/user/logout.do">退出  
  4.   

unauthorized.jsp

[java] view plain copy
  1.   
  2.      认证未通过,或者权限不足  
  3.      "${pageContext.request.contextPath}/user/login.do">退出  
  4.   

6.测试

    根据spring的配置文件中对shiro的url拦截配置,我们首先请求:http://localhost:8080/ShiroSpring/user/admin.do来测试身份认证,然后会跳转到登录页面让我们登录,登录成功后,再次请求这个url就会进入success.jsp页面了。

    再测试角色和权限认证,可以先后输入http://localhost:8080/ShiroSpring/user/student.do来测试角色认证,输入http://localhost:8080/ShiroSpring/user/teacher.do来测试权限认证。通过登陆不同的用户去测试即可。


你可能感兴趣的:(java编程中的问题)