SpringMVC集成shiro和redis

2018-11-26 07:57:06来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

记录用maven集成shiro和redis。

先是代码结构:

 

 

然后是web.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 3 xmlns="http://xmlns.jcp.org/xml/ns/javaee" 
 4 xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" 
 5 metadata-complete="true" version="3.1" >
 6 
 7     <listener>    
 8          <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>    
 9     </listener>
10     <listener>
11          <listener-class>    
12            org.springframework.web.context.request.RequestContextListener    
13          </listener-class>    
14     </listener>
15     
16     <context-param>
17         <param-name>contextConfigLocation</param-name>  
18         <param-value>  
19               classpath*:applicationContext.xml,classpath:spring.xml,classpath:spring-shiro.xml
20         </param-value>  
21     </context-param>
22     
23     <!-- shiro filter 的配置要在别的配置之前,保证能够拦截到所有的请求 -->  
24     <filter>  
25         <filter-name>shiroFilter</filter-name>  
26         <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>  
27         <init-param>  
28             <param-name>targetFilterLifecycle</param-name>  
29             <param-value>true</param-value>  
30         </init-param>  
31     </filter>  
32     <filter-mapping>  
33         <filter-name>shiroFilter</filter-name>  
34         <url-pattern>/*</url-pattern>  
35     </filter-mapping>
36     
37     <!-- 字符编码过滤器 -->
38     <filter>
39         <filter-name>encodingFilter</filter-name>
40         <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
41         <init-param>
42                 <param-name>encoding</param-name>
43                 <param-value>UTF-8</param-value>
44         </init-param>
45         <init-param>
46                 <param-name>forceEncoding</param-name>
47                 <param-value>true</param-value>
48         </init-param>
49     </filter>
50     <filter-mapping>
51         <filter-name>encodingFilter</filter-name>
52         <url-pattern>*.do</url-pattern>
53     </filter-mapping>
54   
55   <servlet>
56     <servlet-name>spring</servlet-name>
57     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
58     <init-param>
59       <param-name>contextConfigLocation</param-name>
60       <param-value>classpath:springMVC.xml</param-value>
61     </init-param>
62     <!-- 这个配置文件在容器启动的时候 就加载 -->  
63     <load-on-startup>1</load-on-startup> 
64   </servlet>
65   <servlet-mapping>
66     <servlet-name>spring</servlet-name>
67     <url-pattern>*.do</url-pattern>
68   </servlet-mapping>
69   
70   <!-- session有效时间 -->
71    <session-config>
72       <session-timeout>30</session-timeout>
73   </session-config>
74   
75   <welcome-file-list>
76     <welcome-file>com/Login.html</welcome-file>
77   </welcome-file-list>
78   
79 </web-app>
web.xml

相关配置文件(放在了src/main/resources下):

首先是springMVC.xml文件,负责扫描,注入,以及控制文件上传,配置拦截器

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"  
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
 4     xmlns:context="http://www.springframework.org/schema/context"
 5     xmlns:aop="http://www.springframework.org/schema/aop" 
 6     xmlns:tx="http://www.springframework.org/schema/tx"
 7     xmlns:mvc="http://www.springframework.org/schema/mvc"  
 8     xsi:schemaLocation=
 9         "http://www.springframework.org/schema/beans 
10          http://www.springframework.org/schema/beans/spring-beans.xsd  
11          http://www.springframework.org/schema/context 
12          http://www.springframework.org/schema/context/spring-context.xsd  
13          http://www.springframework.org/schema/mvc 
14          http://www.springframework.org/schema/mvc/spring-mvc.xsd
15          http://www.springframework.org/schema/aop 
16          http://www.springframework.org/schema/aop/spring-aop.xsd 
17          http://www.springframework.org/schema/tx 
18          http://www.springframework.org/schema/tx/spring-tx.xsd ">                  
19  
20      <!-- 添加注解驱动 -->  
21     <!-- <context:annotation-config />  --> 
22     <!-- 如果使用注释,则必须配置以下设置 -->
23     <mvc:annotation-driven />
24     <!-- 扫描包和子包 -->
25     <context:component-scan base-package="com.ks" />
26     
27     <!-- 注解方式配置事务 -->
28     <tx:annotation-driven transaction-manager="transactionManager" />
29     
30     <!-- 配置事务管理器 -->
31     <bean id="transactionManager"
32         class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
33         <property name="dataSource" ref="dataSource" />
34     </bean>
35     <!-- <mvc:default-servlet-handler/> -->
36     
37     <!-- 配置视图解析器
38         当处理器返回“index”时,InternalResourceViewResolver解析器会自动添加前缀和后缀:/WEB-INF/jsp/index.jsp -->
39      <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
40          <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
41         <!-- 前缀 -->
42         <property name="prefix" value="/WEB-INF/" />
43         <!-- 后缀 -->
44         <!-- <property name="suffix" value=".html" /> -->
45     </bean>
46     
47     <!-- 拦截器 -->  
48     <mvc:interceptors>  
49          <!-- 多个拦截器,顺序执行   -->
50          <mvc:interceptor>  
51              <mvc:mapping path="/**"/>  
52              <bean class="com.ks.top.LoginInterceptor"></bean>  
53          </mvc:interceptor>
54     </mvc:interceptors>
55     
56     <bean id="multipartResolver" 
57       class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
58         <!-- 上传文件大小上限,单位为字节(10MB) -->
59       <property name="maxUploadSize">
60           <value>10485760</value>
61       </property>    
62       <!-- 请求的编码格式,必须和jSP的pageEncoding属性一致,以便正确读取表单的内容,默认为ISO-8859-1 -->  
63       <property name="defaultEncoding">
64         <value>UTF-8</value>
65       </property>  
66   </bean>  
67     
68 </beans>
springMVC.xml

然后是spring.xml(我用来配置redis,数据源,扫描sql文件,)

 

 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:context="http://www.springframework.org/schema/context"  
 5     xmlns:mvc="http://www.springframework.org/schema/mvc" 
 6     xmlns:aop="http://www.springframework.org/schema/aop"  
 7     xmlns:p="http://www.springframework.org/schema/p" 
 8     xsi:schemaLocation="http://www.springframework.org/schema/beans  
 9             http://www.springframework.org/schema/beans/spring-beans.xsd  
10             http://www.springframework.org/schema/mvc  
11             http://www.springframework.org/schema/mvc/spring-mvc.xsd  
12             http://www.springframework.org/schema/context  
13             http://www.springframework.org/schema/context/spring-context.xsd  
14             http://www.springframework.org/schema/aop  
15             http://www.springframework.org/schema/aop/spring-aop.xsd  ">  
16     
17     <!-- <import resource="classpath:mybatisContext.xml"/> -->
18     <!-- 引入配置文件 -->  
19     <bean id="propertyConfigurer"  
20         class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
21         <property name="locations">  
22             <list>  
23                 <value>classpath:configuration.properties</value>  
24                 <value>classpath:redis.properties</value>  
25             </list>  
26         </property>  
27     </bean>
28     <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
29         <property name="driverClassName" value="${jdbc_driverClassName}" />
30         <property name="url" value="${jdbc_url}" />
31         <property name="username" value="${jdbc_username}" />
32         <property name="password" value="${jdbc_password}" />
33     </bean>  
34     
35     <!-- 自动扫描了所有的XxxxMapper.xml对应的mapper接口文件,这样就不用一个一个手动配置Mpper的映射了,只要Mapper接口类和Mapper映射文件对应起来就可以了。 -->
36     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
37         <property name="basePackage" value="com.ks.**.dao" />
38         <property name="sqlSessionFactoryBeanName" value="mySqlSessionFactory" />
39     </bean>
40     
41     <!-- 使用mySqlSessionFactory注入,不会立即初始化sqlSessionFactory, 避免引发提前初始化问题 -->
42     <bean id="mySqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
43         <property name="dataSource" ref="dataSource"/>
44         <!-- <property name="mapperLocations" value="classpath:mapper/**/*.xml"/> -->
45         <property name="configLocation" value="classpath:sqlMapConfig.xml"/>
46     </bean>
47     
48     <!-- 默认扫描的包路径 -->  
49     <context:component-scan base-package="com.ks" />
50     
51 </beans>
spring.xml

redis的配置文件(就一些基础信息,只是用来连通使用而已):

1 redis.ip=localhost
2 redis.port=6379
3 redis.maxActive=5000
4 redis.maxIdle=1000
5 redis.maxWait=3000
redis.properties

spring-shiro.xml(配置shiro。自定义拦截方式,配置拦截类等)

  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:util="http://www.springframework.org/schema/util"
  5     xsi:schemaLocation="
  6         http://www.springframework.org/schema/util  
  7         http://www.springframework.org/schema/util/spring-util.xsd
  8         http://www.springframework.org/schema/beans 
  9         http://www.springframework.org/schema/beans/spring-beans.xsd"
 10     default-lazy-init="true">
 11 
 12     <description>Shiro Configuration</description>
 13     
 14     <!-- 缓存管理器 -->  
 15     <bean id="cacheManager" class="com.ks.shiro.SpringCacheManagerWrapper">  
 16         <property name="cacheManager" ref="springCacheManager" />  
 17     </bean>
 18     
 19     <!-- Realm实现 -->  
 20     <bean id="shiroRealm" class="com.ks.shiro.ShiroRealm">  
 21         <!-- <property name="credentialsMatcher" ref="credentialsMatcher" /> -->  
 22         <!--<property name="cachingEnabled" value="true" />   -->  
 23         <!-- 该项目的登陆认证由登陆操作时自行认证,所以也就不需要使用SHIRO的登陆认证缓存,只使用权限认证缓存,且会重写自带的缓存机制getAuthorizationInfo
 24         <property name="authenticationCachingEnabled" value="true"/>
 25         <property name="authenticationCacheName" value="authenticationCache"/> -->  
 26         <property name="authorizationCachingEnabled" value="true"/>
 27         <property name="authorizationCacheName" value="authorizationCache"/>
 28     </bean>
 29     <!-- 自定义拦截器 -->
 30     <bean id="myShiroFilter" class="com.ks.shiro.ShiroFilter"></bean>
 31     
 32     <!-- 会话ID生成器 -->  
 33     <bean id="sessionIdGenerator"  
 34         class="org.apache.shiro.session.mgt.eis.JavaUuidSessionIdGenerator" />
 35     
 36     <!-- 会话Cookie模板 -->  
 37     <bean id="sessionIdCookie" class="org.apache.shiro.web.servlet.SimpleCookie">  
 38         <constructor-arg value="sid" />  
 39         <property name="httpOnly" value="true" />  
 40         <property name="maxAge" value="-1" />  
 41     </bean>
 42     
 43     <bean id="rememberMeCookie" class="org.apache.shiro.web.servlet.SimpleCookie">  
 44         <constructor-arg value="rememberMe" />  
 45         <property name="httpOnly" value="true" />  
 46         <property name="maxAge" value="2592000" /><!-- 30天 -->  
 47     </bean> 
 48     
 49     <!-- rememberMe管理器 -->  
 50     <bean id="rememberMeManager" class="org.apache.shiro.web.mgt.CookieRememberMeManager">  
 51         <!-- rememberMe cookie加密的密钥 建议每个项目都不一样 默认AES算法 密钥长度(128 256 512 位) -->  
 52         <property name="cipherKey"  
 53             value="#{T(org.apache.shiro.codec.Base64).decode('4AvVhmFLUs0KTA3Kprsdag==')}" />  
 54         <property name="cookie" ref="rememberMeCookie" />  
 55     </bean>
 56     
 57     <!-- 会话DAO -->  
 58     <bean id="sessionDAO"  
 59         class="org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO">  
 60         <property name="activeSessionsCacheName" value="shiro-activeSessionCache" />  
 61         <property name="sessionIdGenerator" ref="sessionIdGenerator" />  
 62     </bean>
 63     
 64     <!-- 会话管理器 -->  
 65     <bean id="sessionManager"  
 66         class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">  
 67         <property name="globalSessionTimeout" value="1800000" />  
 68         <property name="deleteInvalidSessions" value="true" />  
 69         <property name="sessionDAO" ref="customShiroSessionDAO" /><!-- 这里指定shiro的sessionManager使用我们指定的存储方式来存放session信息 -->  
 70         <property name="sessionIdCookieEnabled" value="true" />  
 71         <property name="sessionIdCookie" ref="sessionIdCookie" />  
 72     </bean>
 73     
 74     <bean id="customShiroSessionDAO" class="com.ks.shiro.dao.CustomShiroSessionDao">  
 75         <property name="shiroSessionRepository" ref="jedisShiroSessionRepository" /><!-- 自己定义的sessiondao -->  
 76     </bean>  
 77       
 78       <!-- 配置redis -->
 79     <bean id="jedisShiroSessionRepository"  
 80         class="com.ks.shiro.dao.JedisShiroSessionRepository">  
 81         <property name="redisManager" ref="redisManager"></property>     
 82     </bean>
 83     <!-- 注册上面实现的redisManager到spring中   -->
 84     <bean id="redisManager" class="com.ks.top.redis.RedisManager"></bean>
 85   
 86     <bean id="jedisShiroCacheManager" class="com.ks.shiro.JedisShiroCacheManager">  
 87         <property name="redisManager" ref="redisManager"></property>  
 88     </bean>
 89     <bean id="customShiroCacheManager" class="com.ks.shiro.CustomShiroCacheManager">  
 90         <property name="shrioCacheManager" ref="jedisShiroCacheManager"></property>  
 91     </bean>
 92     <!-- 安全管理器 -->  
 93     <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">  
 94         <property name="realm" ref="shiroRealm" />
 95         <property name="sessionManager" ref="sessionManager" />  
 96         <property name="cacheManager" ref="customShiroCacheManager" />  
 97         <property name="rememberMeManager" ref="rememberMeManager" />  
 98     </bean>
 99     
100     <!-- 相当于调用SecurityUtils.setSecurityManager(securityManager) -->  
101     <bean  
102         class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">  
103         <property name="staticMethod"  
104             value="org.apache.shiro.SecurityUtils.setSecurityManager" />  
105         <property name="arguments" ref="securityManager" />  
106     </bean>
107     
108     <!-- <bean id="sysUserFilter" class="org.calonlan.security.web.shiro.filter.SysUserFilter" /> -->  
109   
110     <!-- Shiro的Web过滤器 -->  
111     <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">  
112         <property name="securityManager" ref="securityManager" />  
113         <!-- 逻辑上正确,不起作用 -->  
114         <!-- <property name="loginUrl" value="/login" />  
115         <property name="successUrl" value="/admin/index" /> -->
116         <property name="unauthorizedUrl" value="/error.html" />
117         <property name="filters">
118             <util:map>  
119                 <!-- 这里是当URL符合制定的拦截规则时。跳转的判断类
120                 <entry key="authc" value-ref="formAuthenticationFilter" /> -->  
121                 <entry key="sysUser" value-ref="myShiroFilter" />  
122             </util:map>  
123         </property>  
124         <property name="filterChainDefinitions">  
125             <value>  
126                 /top/**=anon
127                 /imp/**=anon
128                 /index/userLogin.do=anon
129                 /=anon
130                 /error.html=anon 
131                 /**=anon
132                 <!-- /member/**=sysUser,roles["edit"]  
133                 /edit=sysUser,roles["edit"],perms["delete1"]  
134                 /getJson/**=anon  
135                 /** = sysUser --> 
136             </value>  
137         </property>  
138     </bean> 
139 
140     <!-- 保证实现了Shiro内部lifecycle函数的bean执行 -->
141     <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />
142 
143 </beans>
spring-shiro.xml

数据源的配置文件就不上传了。然后是集成shiro时,用到的代码。还有个applicationContext.xml配置文件,是个空的配置文件,没啥作用

首先是ShiroRealm.java文件(用于验证用户合法性,以及为登陆的用户设置权限。这里为用户设置的角色,权限等,是写死了的。实际上应该从数据库中提取相关数据)

  1 package com.ks.shiro;
  2 
  3 import java.util.ArrayList;
  4 import java.util.List;
  5 
  6 
  7 import org.apache.log4j.Logger;
  8 import org.apache.shiro.SecurityUtils;
  9 import org.apache.shiro.authc.AuthenticationException;
 10 import org.apache.shiro.authc.AuthenticationInfo;
 11 import org.apache.shiro.authc.AuthenticationToken;
 12 import org.apache.shiro.authc.SimpleAuthenticationInfo;
 13 import org.apache.shiro.authc.UsernamePasswordToken;
 14 import org.apache.shiro.authz.AuthorizationException;
 15 import org.apache.shiro.authz.AuthorizationInfo;
 16 import org.apache.shiro.authz.SimpleAuthorizationInfo;
 17 import org.apache.shiro.realm.AuthorizingRealm;
 18 import org.apache.shiro.session.Session;
 19 import org.apache.shiro.subject.PrincipalCollection;
 20 import org.apache.shiro.subject.Subject;
 21 import org.springframework.beans.factory.annotation.Autowired;
 22 
 23 import com.ks.index.model.UserVO;
 24 import com.ks.index.service.IndexService;
 25 import com.ks.shiro.model.Role;
 26 
 27 public class ShiroRealm extends AuthorizingRealm{
 28     
 29     private static final Logger LOG = Logger.getLogger(AuthorizingRealm.class);  
 30 
 31     @Autowired
 32     private IndexService indexService;
 33     
 34     //登陆第二步,通过用户信息将其权限和角色加入作用域中,达到验证的功能
 35     @Override
 36     protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
 37         // 根据用户配置用户与权限
 38         if (principals == null) {  
 39             throw new AuthorizationException(  
 40                     "PrincipalCollection method argument cannot be null.");  
 41         }
 42         String name = (String) getAvailablePrincipal(principals);
 43         List<String> roles = new ArrayList<String>();  
 44         List<String> permissions = new ArrayList<String>();
 45         Subject currentUser = SecurityUtils.getSubject();
 46         Session session = currentUser.getSession();
 47         UserVO userVo = (UserVO) session.getAttribute("user");
 48         if(userVo != null){
 49             // 装配用户的角色和权限 delete  
 50             List<Role> roleList = new ArrayList<Role>();
 51             roleList.add(new Role("role1"));
 52             roleList.add(new Role("role2"));
 53             //String userRole = userVo.getTheRole();
 54             for(Role role : roleList){
 55                 roles.add(role.getName());
 56             }
 57             //permissions.add("delete");  
 58         } else {  
 59             throw new AuthorizationException();  
 60         }  
 61         SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();  
 62         // 为用户设置角色和权限  
 63         info.addRoles(roles);  
 64         info.addStringPermissions(permissions);  
 65         return info;
 66     }
 67 
 68     /**  
 69      * 验证当前登录的Subject  
 70      * @see 经测试:本例中该方法的调用时机为LoginController.login()方法中执行Subject.login()时  
 71      */  
 72     @SuppressWarnings("unused")
 73     @Override
 74     protected AuthenticationInfo doGetAuthenticationInfo(
 75             AuthenticationToken authcToken) throws AuthenticationException {
 76         UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
 77         //下面通过读取token中的数据重新封装了一个user
 78         UserVO userVo = new UserVO();
 79         userVo.setUserAccountNumber(token.getUsername());
 80         userVo = indexService.queryUserByAccount(userVo);
 81         String pwd = new String(token.getPassword());  
 82         if (userVo == null || !pwd.equals(userVo.getUserPassword())){
 83             throw new AuthorizationException("用户名或密码错误");  
 84         }
 85         SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(userVo.getUserAccountNumber(),  
 86                 pwd, getName());  
 87         //将该userVo村放入session作用域中  
 88         this.setSession("user", userVo);
 89         return info;
 90     }
 91     
 92     /**  
 93      * 将一些数据放到ShiroSession中,以便于其它地方使用  
 94      * 比如Controller,使用时直接用HttpSession.getAttribute(key)就可以取到  
 95      */  
 96     @SuppressWarnings("unused")  
 97     private void setSession(Object key, Object value) {  
 98         Subject currentUser = SecurityUtils.getSubject();  
 99         if (null != currentUser) {  
100             Session session = currentUser.getSession();  
101             System.out  
102                     .println("Session默认超时时间为[" + session.getTimeout() + "]毫秒");  
103             if (null != session) {  
104                 session.setAttribute(key, value);  
105             }  
106         }  
107     }
108 
109 }
ShiroRealm.java

然后是我配置的shiro的拦截器(每个请求都会被该拦截器拦截,但可以在配置文件中自定义某些url不被拦截。拦截后,会在这里验证用户的访问权限)

 1 package com.ks.shiro;
 2 
 3 import java.io.IOException;
 4 import java.security.Principal;
 5 
 6 import javax.servlet.Filter;
 7 import javax.servlet.FilterChain;
 8 import javax.servlet.FilterConfig;
 9 import javax.servlet.ServletException;
10 import javax.servlet.ServletRequest;
11 import javax.servlet.ServletResponse;
12 import javax.servlet.http.HttpServletRequest;
13 import javax.servlet.http.HttpServletResponse;
14 
15 import org.apache.shiro.SecurityUtils;
16 import org.apache.shiro.authc.UsernamePasswordToken;
17 import org.apache.shiro.session.Session;
18 import org.apache.shiro.subject.Subject;
19 
20 import com.ks.index.model.UserVO;
21 import com.ks.shiro.model.Role;
22 import com.ks.shiro.model.User;
23 
24 public class ShiroFilter implements Filter{
25 
26     @Override
27     public void destroy() {
28     }
29 
30     @Override
31     public void doFilter(ServletRequest request, ServletResponse response,  
32             FilterChain chain) throws IOException, ServletException {
33         HttpServletRequest httpRequest = (HttpServletRequest) request;  
34         HttpServletResponse httpResponse = (HttpServletResponse) response;  
35         Principal principal = httpRequest.getUserPrincipal();
36         //条件为true说明用户有登陆信息
37         if(principal != null){  
38             Subject subjects = SecurityUtils.getSubject();  
39             // 为了简单,这里初始化一个用户。实际项目项目中应该去数据库里通过名字取用户:  
40             // 例如:User user = userService.getByAccount(principal.getName()); 
41             Subject currentUser = SecurityUtils.getSubject();
42             Session session = currentUser.getSession();
43             UserVO userVo = (UserVO) session.getAttribute("user");
44             //userVo.setRole(new Role(userVo.getTheRole()));
45             if(userVo != null){  
46                 UsernamePasswordToken token = new UsernamePasswordToken(  
47                         userVo.getUserAccountNumber(), userVo.getUserPassword());  
48 //                subjects = SecurityUtils.getSubject();  
49 //                subjects.login(token);
50 //                subjects.getSession();  
51             }else{  
52                 // 如果用户为空,则subjects信息登出  
53 //                if(subjects != null){  
54 //                    subjects.logout();  
55 //                }  
56             }  
57         }  
58         chain.doFilter(httpRequest, httpResponse);
59     }
60 
61     @Override
62     public void init(FilterConfig arg0) throws ServletException {
63     }
64     
65 }
ShiroFilter.java

自定义的CustomShiroSessionDao,该案例中没有用上(用来在shiro中存放,修改一些需要缓存的信息。但一般都用redis来代替该功能了)

 1 package com.ks.shiro.dao;
 2 
 3 import java.io.Serializable;
 4 import java.util.Collection;
 5 
 6 import org.apache.shiro.session.Session;
 7 import org.apache.shiro.session.UnknownSessionException;
 8 import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;
 9 
10 /**
11  * 指定shiro的sessionManager使用指定的
12  * 存储方式存放session信息
13  * @author xushoushan
14  *
15  */
16 public class CustomShiroSessionDao extends AbstractSessionDAO{
17 
18     private ShiroSessionRepository shiroSessionRepository;
19     
20     public ShiroSessionRepository getShiroSessionRepository() {  
21         return shiroSessionRepository;  
22     }  
23   
24     public void setShiroSessionRepository(  
25             ShiroSessionRepository shiroSessionRepository) {  
26         this.shiroSessionRepository = shiroSessionRepository;  
27     }
28     
29     @Override
30     public void delete(Session session) {
31         if (session == null) {  
32             System.out.println("错误");  
33             return;  
34         }  
35         Serializable id = session.getId();  
36         if (id != null)  
37             getShiroSessionRepository().deleteSession(id);
38         
39     }
40 
41     @Override
42     public Collection<Session> getActiveSessions() {
43         return getShiroSessionRepository().getAllSessions(); 
44     }
45 
46     @Override
47     public void update(Session session) throws UnknownSessionException {
48         getShiroSessionRepository().saveSession(session);
49         
50     }
51 
52     @Override
53     protected Serializable doCreate(Session session) {
54         Serializable sessionId = this.generateSessionId(session);  
55         this.assignSessionId(session, sessionId);  
56         getShiroSessionRepository().saveSession(session);  
57         return sessionId;
58     }
59 
60     @Override
61     protected Session doReadSession(Serializable sessionId) {
62         return getShiroSessionRepository().getSession(sessionId);
63     }
64 
65 }
CustomShiroSessionDao

然后是redis涉及的java文件。实际上应该独立一个配置文件来配置才好

先是redis的增删改查:

  1 package com.ks.shiro.dao;
  2 
  3 import java.io.Serializable;
  4 import java.util.Collection;
  5 import java.util.HashSet;
  6 import java.util.Set;
  7 
  8 import org.apache.shiro.session.Session;
  9 
 10 import com.ks.tool.SerializeUtils;
 11 import com.ks.top.redis.RedisManager;
 12 
 13 public class JedisShiroSessionRepository implements ShiroSessionRepository{
 14 
 15     /** 
 16      *  
 17      * redis session key 前缀 
 18      *  
 19      * */  
 20     private final String REDIS_SHIRO_SESSION = "shiro-session";  
 21   
 22     private RedisManager redisManager;  
 23   
 24     @Override  
 25     public void saveSession(Session session) {  
 26         redisManager.init();  
 27         if (session == null || session.getId() == null) {  
 28             System.out.println("session 或者 session ID 为空");  
 29         }  
 30         byte[] key = SerializeUtils.serialize(getRedisSessionKey(session  
 31                 .getId()));  
 32         byte[] value = SerializeUtils.serialize(session);  
 33   
 34         Long timeOut = session.getTimeout() / 1000;  
 35         redisManager.set(key, value, Integer.parseInt(timeOut.toString()));  
 36   
 37     }  
 38   
 39     @Override  
 40     public void deleteSession(Serializable sessionId) {  
 41         redisManager.init();  
 42         if (sessionId == null) {  
 43             System.out.println("id为空");  
 44         }  
 45         redisManager.del(SerializeUtils  
 46                 .serialize(getRedisSessionKey(sessionId)));  
 47   
 48     }  
 49   
 50     @Override  
 51     public Session getSession(Serializable sessionId) {  
 52         redisManager.init();  
 53         if (null == sessionId) {  
 54             System.out.println("id为空");  
 55             return null;  
 56         }  
 57         Session session = null;  
 58         byte[] value = redisManager.get(SerializeUtils  
 59                 .serialize(getRedisSessionKey(sessionId)));  
 60         if (null == value)  
 61             return null;  
 62         session = (Session) SerializeUtils.deserialize(value);  
 63         return session;  
 64     }  
 65   
 66     @Override  
 67     public Collection<Session> getAllSessions() {  
 68         redisManager.init();  
 69         Set<Session> sessions = new HashSet<Session>();  
 70         Set<byte[]> byteKeys = redisManager  
 71                 .keys(this.REDIS_SHIRO_SESSION + "*");  
 72         if (byteKeys != null && byteKeys.size() > 0) {  
 73             for (byte[] bs : byteKeys) {  
 74                 Session s = (Session) SerializeUtils.deserialize(redisManager  
 75                         .get(bs));  
 76                 sessions.add(s);  
 77             }  
 78         }  
 79         return sessions;  
 80     }  
 81   
 82     /** 
 83      * 获取redis中的session key 
 84      *  
 85      * @param sessionId 
 86      * @return 
 87      */  
 88     private String getRedisSessionKey(Serializable sessionId) {  
 89         return this.REDIS_SHIRO_SESSION + sessionId;  
 90     }  
 91   
 92     public RedisManager getRedisManager() {  
 93         return redisManager;  
 94     }  
 95   
 96     public void setRedisManager(RedisManager redisManager) {  
 97         this.redisManager = redisManager;  
 98     }  
 99   
100     public JedisShiroSessionRepository() {  
101   
102     }  
103   
104     // public static void main(String[] args) {  
105     // Jedis jj = new Jedis("localhost");  
106     // //jj.set("key2", "232323231=========");  
107     // String ss = jj.get("key1");  
108     // System.out.println(jj.get("key2"));  
109     // System.out.println(ss);  
110     // }
111 
112 }
JedisShiroSessionRepository

JedisShiroSessionRepository所实现的接口类:

 1 package com.ks.shiro.dao;
 2 
 3 import java.io.Serializable;
 4 import java.util.Collection;
 5 
 6 import org.apache.shiro.session.Session;
 7 
 8 /**
 9  * 进行详细的session存储操作
10  * @author xushoushan
11  *
12  */
13 public interface ShiroSessionRepository {
14     void saveSession(Session session);  
15       
16     void deleteSession(Serializable sessionId);  
17   
18     Session getSession(Serializable sessionId);  
19   
20     Collection<Session> getAllSessions();
21 }
ShiroSessionRepository

redis的链接类:

  1 package com.ks.top.redis;
  2 
  3 import java.util.Iterator;
  4 import java.util.Set;
  5 
  6 import org.springframework.beans.factory.annotation.Value;
  7 
  8 import redis.clients.jedis.Jedis;
  9 import redis.clients.jedis.JedisPool;
 10 import redis.clients.jedis.JedisPoolConfig;
 11 
 12 /**
 13  * redismanager主要用来给用户提供一个设计完备的,通过jedis的jar包来管理redis内存数据库的各种方法
 14  * @author xushoushan
 15  *
 16  */
 17 public class RedisManager {
 18     // ip和port属性都定义在了properties文件中,这里通过spring的注解方式来直接使用  
 19     @Value("${redis.ip}")
 20     private String host;
 21     @Value("${redis.port}")
 22     private int port;
 23     @Value("${redis.maxActive}")
 24     private int maxActive;
 25     @Value("${redis.maxIdle}")
 26     private int maxIdle;
 27     @Value("${redis.maxWait}")
 28     private int maxWait;
 29   
 30     // 设置为0的话就是永远都不会过期  
 31     private int expire = 0;  
 32     
 33     // 定义一个管理池,所有的redisManager共同使用。  
 34     private static JedisPool jedisPool = null;
 35     
 36     public RedisManager() {  
 37     }  
 38   
 39     /** 
 40      *  
 41      * 初始化方法,在这个方法中通过host和port来初始化jedispool。 
 42      *  
 43      * */  
 44   
 45     public void init() {  
 46         if (null == host || 0 == port) {  
 47             System.out.println("请初始化redis配置文件");  
 48             throw new NullPointerException("找不到redis配置");  
 49         }  
 50         if (jedisPool == null) {
 51             JedisPoolConfig config = new JedisPoolConfig();
 52             //设置最大连接数
 53             //config.setMaxTotal(maxActive);
 54             //设置最大空闲数
 55             config.setMaxIdle(maxIdle);
 56             //设置超时时间
 57             config.setMaxWait(maxWait);
 58             jedisPool = new JedisPool(config, host, port);
 59         }  
 60     }  
 61   
 62     /** 
 63      * get value from redis 
 64      *  
 65      * @param key 
 66      * @return 
 67      */  
 68     public byte[] get(byte[] key) {  
 69         byte[] value = null;  
 70         Jedis jedis = jedisPool.getResource();  
 71         try {  
 72             value = jedis.get(key);  
 73         } finally {  
 74             jedisPool.returnResource(jedis);  
 75         }  
 76         return value;  
 77     }  
 78   
 79     /** 
 80      * get value from redis 
 81      * 通过keycongredis中取值
 82      * @param key 
 83      * @return 
 84      */  
 85 //    public String get(String key) {  
 86 //        String value = null;  
 87 //        Jedis jedis = jedisPool.getResource();  
 88 //        try {  
 89 //            value = jedis.get(key);  
 90 //        } finally {  
 91 //            jedisPool.returnResource(jedis);  
 92 //        }  
 93 //        return value;  
 94 //    }
 95     
 96     /**
 97      * 根据key 获取内容
 98      *
 99      * @param key
100      * @return
101      */
102     public static Object get(String key) {
103         Jedis jedis = null;
104         try {
105             jedis = jedisPool.getResource();
106             byte[] value = jedis.get(key.getBytes());
107             return SerializeUtil.unserialize(value);
108         } catch (Exception e) {
109             e.printStackTrace();
110             return false;
111         } finally {
112             jedisPool.returnResource(jedis);
113         }
114     }
115   
116     /** 
117      * set 
118      *  
119      * @param key 
120      * @param value 
121      * @return 
122      */  
123     public byte[] set(byte[] key, byte[] value) {  
124         Jedis jedis = jedisPool.getResource();  
125         try {  
126             jedis.set(key, value);  
127             if (this.expire != 0) {  
128                 jedis.expire(key, this.expire);  
129             }  
130         } finally {  
131             jedisPool.returnResource(jedis);  
132         }  
133         return value;  
134     }  
135   
136     /** 
137      * set 
138      *  
139      * @param key 
140      * @param value 
141      * @return 
142      */  
143     public String set(String key, String value) {  
144         Jedis jedis = jedisPool.getResource();  
145         try {  
146             jedis.set(key, value);  
147             if (this.expire != 0) {  
148                 jedis.expire(key, this.expire);  
149             }  
150         } finally {  
151             jedisPool.returnResource(jedis);  
152         }  
153         return value;  
154     }  
155   
156     /** 
157      * set 
158      *  
159      * @param key 
160      * @param value 
161      * @param expire 
162      * @return 
163      */  
164     public byte[] set(byte[] key, byte[] value, int expire) {  
165         Jedis jedis = jedisPool.getResource();  
166         try {  
167             jedis.set(key, value);  
168             if (expire != 0) {  
169                 jedis.expire(key, expire);  
170             }  
171         } finally {  
172             jedisPool.returnResource(jedis);  
173         }  
174         return value;  
175     }
176     
177     /** 
178      * set 
179      *  
180      * @param key     缓存凭据
181      * @param value     缓存对象
182      * @param expire  有效时间
183      * @return 
184      */  
185     public boolean set(String key, Object value, int expire) {  
186         Jedis jedis = jedisPool.getResource();  
187         try {  
188             jedis.set(key.getBytes(), SerializeUtil.serialize(value));
189             if (expire != 0) {  
190                 jedis.expire(key.getBytes(), expire);  
191             }
192             return true;
193         }catch(Exception e){
194             return false;
195         } finally {  
196             jedisPool.returnResource(jedis);  
197         }
198     }
199   
200     /** 
201      * set 
202      *  
203      * @param key 
204      * @param value 
205      * @param expire 
206      * @return 
207      */  
208 //    public String set(String key, String value, int expire) {  
209 //        Jedis jedis = jedisPool.getResource();  
210 //        try {  
211 //            jedis.set(key, value);  
212 //            if (expire != 0) {  
213 //                jedis.expire(key, expire);  
214 //            }  
215 //        } finally {  
216 //            jedisPool.returnResource(jedis);  
217 //        }  
218 //        return value;  
219 //    }  
220   
221     /** 
222      * del 
223      *  
224      * @param key 
225      */  
226     public void del(byte[] key) {  
227         Jedis jedis = jedisPool.getResource();  
228         try {  
229             jedis.del(key);  
230         } finally {  
231             jedisPool.returnResource(jedis);  
232         }  
233     }  
234   
235     /** 
236      * del 
237      *  
238      * @param key 
239      */  
240     public void del(String key) {  
241         Jedis jedis = jedisPool.getResource();  
242         try {  
243             jedis.del(key);  
244         } finally {  
245             jedisPool.returnResource(jedis);  
246         }  
247     }  
248   
249     /** 
250      * flush 
251      */  
252     public void flushDB() {  
253         Jedis jedis = jedisPool.getResource();  
254         try {  
255             jedis.flushDB();  
256         } finally {  
257             jedisPool.returnResource(jedis);  
258         }  
259     }  
260   
261     /** 
262      * size 
263      */  
264     public Long dbSize() {  
265         Long dbSize = 0L;  
266         Jedis jedis = jedisPool.getResource();  
267         try {  
268             dbSize = jedis.dbSize();  
269         } finally {  
270             jedisPool.returnResource(jedis);  
271         }  
272         return dbSize;  
273     }  
274   
275     /** 
276      * keys 
277      *  
278      * @param regex 
279      * @return 
280      */  
281     public Set<byte[]> keys(String pattern) {  
282         Set<byte[]> keys = null;  
283         Jedis jedis = jedisPool.getResource();  
284         try {  
285             keys = jedis.keys(pattern.getBytes());  
286         } finally {  
287             jedisPool.returnResource(jedis);  
288         }  
289         return keys;  
290     }  
291   
292     public void dels(String pattern) {  
293         Set<byte[]> keys = null;  
294         Jedis jedis = jedisPool.getResource();  
295         try {  
296             keys = jedis.keys(pattern.getBytes());  
297             Iterator<byte[]> ito = keys.iterator();  
298             while (ito.hasNext()) {  
299                 jedis.del(ito.next());  
300             }  
301         } finally {  
302             jedisPool.returnResource(jedis);  
303         }  
304     }  
305   
306     public String getHost() {  
307         return host;  
308     }  
309   
310     public void setHost(String host) {  
311         this.host = host;  
312     }  
313   
314     public int getPort() {  
315         return port;  
316     }  
317   
318     public void setPort(int port) {  
319         this.port = port;  
320     }  
321   
322     public int getExpire() {  
323         return expire;  
324     }  
325   
326     public void setExpire(int expire) {  
327         this.expire = expire;  
328     }
329 
330     public int getMaxActive() {
331         return maxActive;
332     }
333 
334     public void setMaxActive(int maxActive) {
335         this.maxActive = maxActive;
336     }
337 
338     public int getMaxIdle() {
339         return maxIdle;
340     }
341 
342     public void setMaxIdle(int maxIdle) {
343         this.maxIdle = maxIdle;
344     }
345 
346     public int getMaxWait() {
347         return maxWait;
348     }
349 
350     public void setMaxWait(int maxWait) {
351         this.maxWait = maxWait;
352     } 
353     
354 }
RedisManager

redis和shiro所结合的工具类,提供给shiro使用

 1 package com.ks.shiro;
 2 
 3 import org.apache.shiro.cache.Cache;
 4 
 5 import com.ks.top.redis.RedisManager;
 6 
 7 public class JedisShiroCacheManager implements ShiroCacheManager{
 8 
 9     private RedisManager redisManager;  
10       
11     public RedisManager getRedisManager() {  
12         return redisManager;  
13     }  
14   
15     public void setRedisManager(RedisManager redisManager) {  
16         this.redisManager = redisManager;  
17     }  
18   
19     @Override  
20     public <K, V> Cache<K, V> getCache(String name) {
21         return new JedisShiroCache<K, V>(redisManager, name);  
22     }  
23   
24     @Override  
25     public void destroy() {  
26         redisManager.init();  
27         redisManager.flushDB();  
28     }
29 
30 }
JedisShiroCacheManager

JedisShiroCacheManager实现的接口类

1 package com.ks.shiro;
2 
3 import org.apache.shiro.cache.Cache;
4 
5 public interface ShiroCacheManager {
6     <K, V> Cache<K, V> getCache(String name);    
7     
8     void destroy();
9 }
ShiroCacheManager
 1 package com.ks.shiro;
 2 
 3 import org.apache.shiro.cache.Cache;
 4 import org.apache.shiro.cache.CacheException;
 5 import org.apache.shiro.cache.CacheManager;
 6 
 7 public class CustomShiroCacheManager implements CacheManager{
 8     
 9     private ShiroCacheManager shrioCacheManager;
10 
11     public ShiroCacheManager getShrioCacheManager() {  
12         return shrioCacheManager;  
13     }  
14   
15     public void setShrioCacheManager(ShiroCacheManager shrioCacheManager) {  
16         this.shrioCacheManager = shrioCacheManager;  
17     }  
18   
19     @Override  
20     public <K, V> Cache<K, V> getCache(String name) throws CacheException {  
21         return getShrioCacheManager().getCache(name);  
22     }
23 }
CustomShiroCacheManager

缓存管理器:

  1 package com.ks.shiro;
  2 
  3 import java.util.ArrayList;
  4 import java.util.Collection;
  5 import java.util.Collections;
  6 import java.util.HashSet;
  7 import java.util.List;
  8 import java.util.Set;
  9 
 10 import net.sf.ehcache.Ehcache;
 11 
 12 import org.apache.shiro.cache.Cache;
 13 import org.apache.shiro.cache.CacheException;
 14 import org.apache.shiro.cache.CacheManager;
 15 import org.apache.shiro.util.CollectionUtils;
 16 import org.springframework.cache.support.SimpleValueWrapper;
 17 
 18 public class SpringCacheManagerWrapper implements CacheManager{
 19     private org.springframework.cache.CacheManager cacheManager;  
 20       
 21     /** 
 22      * 设置spring cache manager 
 23      * 
 24      * @param cacheManager 
 25      */  
 26     public void setCacheManager(org.springframework.cache.CacheManager cacheManager) {  
 27         this.cacheManager = cacheManager;  
 28     }  
 29   
 30     @Override  
 31     public <K, V> Cache<K, V> getCache(String name) throws CacheException {  
 32         org.springframework.cache.Cache springCache = cacheManager.getCache(name);  
 33         return new SpringCacheWrapper(springCache);  
 34     }  
 35   
 36     static class SpringCacheWrapper implements Cache {  
 37         private org.springframework.cache.Cache springCache;  
 38   
 39         SpringCacheWrapper(org.springframework.cache.Cache springCache) {  
 40             this.springCache = springCache;  
 41         }  
 42   
 43         @Override  
 44         public Object get(Object key) throws CacheException {  
 45             Object value = springCache.get(key);  
 46             if (value instanceof SimpleValueWrapper) {  
 47                 return ((SimpleValueWrapper) value).get();  
 48             }  
 49             return value;  
 50         }  
 51   
 52         @Override  
 53         public Object put(Object key, Object value) throws CacheException {  
 54             springCache.put(key, value);  
 55             return value;  
 56         }  
 57   
 58         @Override  
 59         public Object remove(Object key) throws CacheException {  
 60             springCache.evict(key);  
 61             return null;  
 62         }  
 63   
 64         @Override  
 65         public void clear() throws CacheException {  
 66             springCache.clear();  
 67         }  
 68   
 69         @Override  
 70         public int size() {  
 71             if(springCache.getNativeCache() instanceof Ehcache) {  
 72                 Ehcache ehcache = (Ehcache) springCache.getNativeCache();  
 73                 return ehcache.getSize();  
 74             }
 75             throw new UnsupportedOperationException("invoke spring cache abstract size method not supported");  
 76         }  
 77   
 78         @Override  
 79         public Set keys() {  
 80             if(springCache.getNativeCache() instanceof Ehcache) {  
 81                 Ehcache ehcache = (Ehcache) springCache.getNativeCache();  
 82                 return new HashSet(ehcache.getKeys());  
 83             }  
 84             throw new UnsupportedOperationException("invoke spring cache abstract keys method not supported");  
 85         }  
 86   
 87         @Override  
 88         public Collection values() {  
 89             if(springCache.getNativeCache() instanceof Ehcache) {  
 90                 Ehcache ehcache = (Ehcache) springCache.getNativeCache();  
 91                 List keys = ehcache.getKeys();  
 92                 if (!CollectionUtils.isEmpty(keys)) {  
 93                     List values = new ArrayList(keys.size());  
 94                     for (Object key : keys) {  
 95                         Object value = get(key);  
 96                         if (value != null) {  
 97                             values.add(value);  
 98                         }  
 99                     }  
100                     return Collections.unmodifiableList(values);  
101                 } else {  
102                     return Collections.emptyList();  
103                 }  
104             }  
105             throw new UnsupportedOperationException("invoke spring cache abstract values method not supported");  
106         }  
107     }
108 }
SpringCacheManagerWrapper

最后是登陆时涉及的controller

  1 package com.ks.index.controller;
  2 
  3 import java.sql.Timestamp;
  4 import java.util.Date;
  5 import java.util.HashMap;
  6 import java.util.Map;
  7 import java.util.UUID;
  8 
  9 import javax.servlet.http.HttpServletRequest;
 10 import javax.servlet.http.HttpServletResponse;
 11 import javax.servlet.http.HttpSession;
 12 
 13 import org.apache.log4j.Logger;
 14 import org.apache.shiro.SecurityUtils;
 15 import org.apache.shiro.authc.AuthenticationException;
 16 import org.apache.shiro.authc.UsernamePasswordToken;
 17 import org.apache.shiro.subject.Subject;
 18 import org.springframework.beans.factory.annotation.Autowired;
 19 import org.springframework.stereotype.Controller;
 20 import org.springframework.web.bind.annotation.RequestBody;
 21 import org.springframework.web.bind.annotation.RequestMapping;
 22 import org.springframework.web.bind.annotation.ResponseBody;
 23 
 24 
 25 
 26 import com.ks.index.model.UserVO;
 27 import com.ks.index.service.IndexService;
 28 
 29 
 30 @Controller
 31 @RequestMapping("/index")
 32 public class IndexController{
 33     
 34     private static final Logger LOG = Logger.getLogger(IndexController.class);  
 35 
 36     @Autowired
 37     private IndexService indexService; 
 38     
 39     /**
 40      * 登陆账号
 41      * @param session
 42      * @param req
 43      * @param res
 44      * @return
 45      */
 46     @RequestMapping("/userLogin")
 47     @ResponseBody
 48     public Map<String,Object> HandleIndexSome(HttpSession session,HttpServletRequest req,HttpServletResponse res){
 49         Map<String,Object> ret = new HashMap<String,Object>();
 50 //        if("".equals(req.getParameter("username"))){
 51 //            ret.put("notUser", "notUser");
 52 //            return ret;
 53 //        }
 54         //用户名跟密码组成Token
 55         UsernamePasswordToken token = new UsernamePasswordToken(req.getParameter("username"),
 56                 req.getParameter("pasword"));
 57         Subject subject = SecurityUtils.getSubject();
 58         token.setRememberMe(true);
 59         //验证角色和权限  
 60         try {
 61             subject.login(token);
 62             ret.put("success", "认证成功");
 63         } catch (AuthenticationException e) {
 64             e.printStackTrace();
 65             ret.put("error", "用户名或密码错误");
 66         }
 67         String userName = req.getParameter("username");
 68         session.setAttribute("userName", userName);
 69         session.setAttribute("userId", "1565256");
 70         return ret;
 71     }
 72 
 73     /**
 74      * 注册账号
 75      * @param vo:页面填写的信息
 76      * @return
 77      */
 78     @ResponseBody
 79     @RequestMapping(value="/registerUser")
 80     public int RegisterUser(@RequestBody UserVO vo){
 81         if("".equals(vo.getId()) || vo.getId() == null){
 82             //新建用户
 83             vo.setId(UUID.randomUUID().toString().replaceAll("-", ""));
 84             vo.setCreateDate(new Timestamp(System.currentTimeMillis()));
 85         }
 86         vo.setLastUpdateDate(new Timestamp(System.currentTimeMillis()));
 87         int i = indexService.saveUser(vo);
 88         return i;
 89     }
 90     
 91     
 92     @RequestMapping(value="/queryUserSession")
 93     @ResponseBody
 94     public Map<String,Object> QueryUserSession(HttpServletRequest request, HttpServletResponse response,
 95             Object arg2){
 96         Map<String,Object> ret = new HashMap<String,Object>();
 97         HttpSession session = request.getSession();
 98         String username = (String)session.getAttribute("userName");
 99         if(username != null){
100             ret.put("userName",username);
101             return ret;
102         }else{
103             ret.put("userName","off");
104             return ret;
105         }
106         //不符合条件的,跳转到登录界面
107         //request.getRequestDispatcher("com/Login.html").forward(request, response);
108     }
109     
110 }
IndexController

最后说一下。indexController里面的subject.login(token)方法。会触发ShiroRealm.java里的doGetAuthenticationInfo方法。我备注里面有,在这里会验证用户的合法性。并且可以进行数据的缓存。

 

我的sql文件存放在mapper文件夹中。jsp放在WEB-INF下

对了。还有pom文件

  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.mssmm</groupId>
  4   <artifactId>MaSSMyMy</artifactId>
  5   <version>0.0.1-SNAPSHOT</version>
  6   <packaging>war</packaging>
  7   <url>http://maven.apache.org</url>
  8   
  9   <properties>
 10         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 11         <cxf.version>3.0.2</cxf.version>
 12         <slf4j.version>1.7.6</slf4j.version>
 13         <spring.version>4.0.2.RELEASE</spring.version>
 14         <jackson.version>2.5.0</jackson.version>
 15     </properties>
 16     <dependencyManagement>
 17         <dependencies>
 18             <dependency>
 19                 <groupId>org.apache.cxf</groupId>
 20                 <artifactId>cxf-rt-frontend-jaxws</artifactId>
 21                 <version>${cxf.version}</version>
 22             </dependency>
 23             <dependency>
 24                 <groupId>org.apache.cxf</groupId>
 25                 <artifactId>cxf-rt-transports-http</artifactId>
 26                 <version>${cxf.version}</version>
 27             </dependency>
 28             <dependency>
 29                 <groupId>org.apache.cxf</groupId>
 30                 <artifactId>cxf-rt-frontend-jaxws</artifactId>
 31                 <version>${cxf.version}</version>
 32             </dependency>
 33             <dependency>
 34                 <groupId>org.slf4j</groupId>
 35                 <artifactId>slf4j-jcl</artifactId>
 36                 <version>${slf4j.version}</version>
 37             </dependency>
 38             <dependency>
 39                 <groupId>commons-discovery</groupId>
 40                 <artifactId>commons-discovery</artifactId>
 41                 <version>0.5</version>
 42             </dependency>
 43             <dependency>
 44                 <groupId>org.apache.cxf</groupId>
 45                 <artifactId>cxf-tools-wsdlto-core</artifactId>
 46                 <version>${cxf.version}</version>
 47             </dependency>
 48             <dependency>
 49                 <groupId>org.apache.cxf</groupId>
 50                 <artifactId>cxf-tools-wsdlto-frontend-jaxws</artifactId>
 51                 <version>${cxf.version}</version>
 52             </dependency>
 53             <dependency>
 54                 <groupId>org.apache.cxf</groupId>
 55                 <artifactId>cxf-tools-wsdlto-databinding-jaxb</artifactId>
 56                 <version>${cxf.version}</version>
 57             </dependency>
 58         </dependencies>
 59     </dependencyManagement>
 60   <dependencies>
 61     <dependency>
 62       <groupId>junit</groupId>
 63       <artifactId>junit</artifactId>
 64       <version>3.8.1</version>
 65       <scope>test</scope>
 66     </dependency>
 67     <dependency>
 68         <groupId>javax.servlet</groupId>
 69         <artifactId>servlet-api</artifactId>
 70         <version>2.4</version>
 71     </dependency>
 72     <!-- spring begin -->
 73     <dependency>
 74         <groupId>org.springframework</groupId>
 75         <artifactId>spring-webmvc</artifactId>
 76         <version>${spring.version}</version>
 77     </dependency>
 78     <dependency>
 79         <groupId>org.springframework</groupId>
 80         <artifactId>spring-jdbc</artifactId>
 81         <version>${spring.version}</version>
 82     </dependency>
 83     <dependency>
 84         <groupId>org.springframework</groupId>
 85         <artifactId>spring-context</artifactId>
 86         <version>${spring.version}</version>
 87     </dependency>
 88     <dependency>
 89         <groupId>org.springframework</groupId>
 90         <artifactId>spring-tx</artifactId>
 91         <version>${spring.version}</version>
 92     </dependency>
 93     <dependency>
 94         <groupId>org.springframework</groupId>
 95         <artifactId>spring-beans</artifactId>
 96         <version>${spring.version}</version>
 97     </dependency>
 98     <dependency>
 99         <groupId>org.springframework</groupId>
100         <artifactId>spring-aop</artifactId>
101         <version>${spring.version}</version>
102     </dependency>
103     <dependency>
104         <groupId>org.springframework</groupId>
105         <artifactId>spring-aspects</artifactId>
106         <version>${spring.version}</version>
107     </dependency>
108     <dependency>
109         <groupId>org.springframework</groupId>
110         <artifactId>spring-core</artifactId>
111         <version>${spring.version}</version>
112     </dependency>
113     <dependency>
114         <groupId>org.springframework</groupId>
115         <artifactId>spring-test</artifactId>
116         <version>${spring.version}</version>
117     </dependency>
118     <dependency>
119         <groupId>org.springframework</groupId>
120         <artifactId>spring-web</artifactId>
121         <version>4.0.2.RELEASE</version>
122     </dependency>
123     <!-- spring end -->
124     <!-- web jar -->
125     <dependency>
126         <groupId>javax.servlet</groupId>
127         <artifactId>javax.servlet-api</artifactId>
128         <version>3.0.1</version>
129         <scope>provided</scope>
130     </dependency>
131     <!-- <dependency>
132         <groupId>javax.servlet</groupId>
133         <artifactId>jstl</artifactId>
134         <version>1.2</version>
135         <scope>provided</scope>
136     </dependency> -->
137     <dependency>
138         <groupId>javax.servlet</groupId>
139         <artifactId>javax.servlet-api</artifactId>
140         <version>3.0.1</version>
141         <scope>provided</scope>
142     </dependency>
143     <dependency>
144         <groupId>javax.servlet.jsp</groupId>
145         <artifactId>jsp-api</artifactId>
146         <version>2.2</version>
147         <scope>provided</scope>
148     </dependency>
149     <dependency>
150         <groupId>javax.servlet.jsp</groupId>
151         <artifactId>javax.servlet.jsp-api</artifactId>
152         <version>2.3.1</version>
153         <scope>provided</scope>
154     </dependency>
155     <!-- jackson jar -->
156     <dependency>
157         <groupId>org.codehaus.jackson</groupId>
158         <artifactId>jackson-jaxrs</artifactId>
159         <version>1.9.11</version>
160     </dependency>
161     <!-- commons jar -->
162     <dependency>
163         <groupId>org.apache.commons</groupId>
164         <artifactId>commons-lang3</artifactId>
165         <version>3.3.2</version>
166     </dependency>
167     <dependency>
168         <groupId>commons-io</groupId>
169         <artifactId>commons-io</artifactId>
170         <version>2.4</version>
171     </dependency>
172     <dependency>
173         <groupId>org.apache.commons</groupId>
174         <artifactId>commons-collections4</artifactId>
175         <version>4.0</version>
176     </dependency>
177     <dependency>
178         <groupId>commons-logging</groupId>
179         <artifactId>commons-logging</artifactId>
180         <version>1.1.3</version>
181     </dependency>
182     <dependency>
183         <groupId>commons-codec</groupId>
184         <artifactId>commons-codec</artifactId>
185         <version>1.8</version>
186     </dependency>
187     <dependency>
188         <groupId>commons-beanutils</groupId>
189         <artifactId>commons-beanutils</artifactId>
190         <version>1.8.3</version>
191     </dependency>
192     <dependency>
193         <groupId>commons-chain</groupId>
194         <artifactId>commons-chain</artifactId>
195         <version>1.2</version>
196     </dependency>
197     <dependency>
198         <groupId>commons-fileupload</groupId>
199         <artifactId>commons-fileupload</artifactId>
200         <version>1.3.1</version>
201     </dependency>
202     <dependency>
203         <groupId>org.apache.commons</groupId>
204         <artifactId>commons-math3</artifactId>
205         <version>3.3</version>
206     </dependency>
207     <dependency>
208         <groupId>org.apache.commons</groupId>
209         <artifactId>commons-pool2</artifactId>
210         <version>2.2</version>
211     </dependency>
212     <dependency>
213         <groupId>org.apache.commons</groupId>
214         <artifactId>commons-digester3</artifactId>
215         <version>3.2</version>
216     </dependency>
217     <dependency>
218         <groupId>commons-net</groupId>
219         <artifactId>commons-net</artifactId>
220         <version>3.3</version>
221     </dependency>
222     <dependency>
223         <groupId>commons-dbutils</groupId>
224         <artifactId>commons-dbutils</artifactId>
225         <version>1.5</version>
226     </dependency>
227     <dependency>
228         <groupId>org.apache.commons</groupId>
229         <artifactId>commons-email</artifactId>
230         <version>1.3.3</version>
231     </dependency>
232     <dependency>
233         <groupId>commons-dbcp</groupId>
234         <artifactId>commons-dbcp</artifactId>
235         <version>1.4</version>
236     </dependency>
237     <!-- jstl jar -->
238     <dependency>
239         <groupId>jstl</groupId>
240         <artifactId>jstl</artifactId>
241         <version>1.2</version>
242     </dependency>
243     <dependency>
244         <groupId>taglibs</groupId>
245         <artifactId>standard</artifactId>
246         <version>1.1.2</version>
247     </dependency>
248     <!-- 日志相关 -->
249     <dependency>
250         <groupId>log4j</groupId>
251         <artifactId>log4j</artifactId>
252         <version>1.2.16</version>
253     </dependency>
254     <dependency>
255         <groupId>org.slf4j</groupId>
256         <artifactId>slf4j-api</artifactId>
257         <version>1.7.5</version>
258     </dependency>
259     <dependency>  
260         <groupId>org.slf4j</groupId>  
261         <artifactId>slf4j-log4j12</artifactId>  
262         <version>1.7.5</version>  
263     </dependency>
264     <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjrt -->  
265     <dependency>  
266       <groupId>org.aspectj</groupId>  
267       <artifactId>aspectjrt</artifactId>  
268       <version>1.8.9</version>  
269     </dependency>  
270     <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjtools -->  
271     <dependency>  
272       <groupId>org.aspectj</groupId>  
273       <artifactId>aspectjtools</artifactId>  
274       <version>1.8.9</version>  
275     </dependency>  
276     <dependency>  
277       <groupId>org.aspectj</groupId>  
278       <artifactId>aspectjweaver</artifactId>  
279       <version>1.7.4</version>  
280     </dependency>  
281     <dependency>  
282       <groupId>org.apache.maven.plugins</groupId>  
283       <artifactId>maven-clean-plugin</artifactId>  
284       <version>2.4.1</version>  
285     </dependency>  
286     <dependency>  
287       <groupId>org.apache.maven.plugins</groupId>  
288       <artifactId>maven-clean-plugin</artifactId>  
289       <version>2.4.1</version>  
290     </dependency>
291     <dependency>
292         <groupId>javax</groupId>
293         <artifactId>javaee-api</artifactId>
294         <version>7.0</version>
295         <scope>provided</scope>
296     </dependency>
297     <!-- ibatis -->
298     <dependency>
299         <groupId>org.mybatis</groupId>
300         <artifactId>mybatis</artifactId>
301         <version>3.2.8</version>
302     </dependency>
303     <!--mybatis spring 插件 -->
304     <dependency>
305         <groupId>org.mybatis</groupId>
306         <artifactId>mybatis-spring</artifactId>
307         <version>1.2.2</version>
308     </dependency>
309     <!-- mysql连接 -->
310     <dependency>
311         <groupId>mysql</groupId>
312         <artifactId>mysql-connector-java</artifactId>
313         <version>5.1.34</version>
314     </dependency>
315     <!-- json -->
316     <dependency>
317         <groupId>org.codehaus.jackson</groupId>
318         <artifactId>jackson-mapper-asl</artifactId>
319         <version>1.9.13</version>
320     </dependency>
321     <dependency>
322         <groupId>com.fasterxml.jackson.core</groupId>
323         <artifactId>jackson-annotations</artifactId>
324         <version>${jackson.version}</version> 
325     </dependency>
326     <dependency>
327         <groupId>com.fasterxml.jackson.core</groupId>
328         <artifactId>jackson-core</artifactId>
329         <version>${jackson.version}</version>
330     </dependency>
331     <dependency>
332         <groupId>org.codehaus.jackson</groupId>
333         <artifactId>jackson-core-asl</artifactId>
334         <version>1.9.13</version>
335     </dependency>
336     <dependency>
337         <groupId>com.fasterxml.jackson.core</groupId>
338         <artifactId>jackson-databind</artifactId>
339         <version>${jackson.version}</version>
340     </dependency>
341     <!-- oracle -->
342     <!-- <dependency>
343           <groupId>com.oracle</groupId>
344           <artifactId>ojdbc6</artifactId>
345           <version>11.2.0.4.0</version>
346       </dependency> -->
347       
348         <!--spring单元测试依赖 -->
349         <dependency>
350             <groupId>org.springframework</groupId>
351             <artifactId>spring-test</artifactId>
352             <version>4.0.2.RELEASE</version>
353             <scope>test</scope>
354         </dependency>
355         
356         <!-- mysql驱动包 -->
357         <dependency>
358             <groupId>mysql</groupId>
359             <artifactId>mysql-connector-java</artifactId>
360             <version>5.1.29</version>
361         </dependency>
362         
363         <!-- shiro -->
364         <dependency>  
365             <groupId>org.apache.shiro</groupId>  
366             <artifactId>shiro-all</artifactId>  
367             <version>1.2.2</version>
368         </dependency>
369         <dependency>
370             <groupId>org.apache.shiro</groupId>
371             <artifactId>shiro-quartz</artifactId>
372             <version>1.2.3</version>
373         </dependency>
374         
375         <!-- redis -->
376         <dependency>
377             <groupId>redis.clients</groupId>
378             <artifactId>jedis</artifactId>
379             <version>2.1.0</version>
380         </dependency> 
381         
382         <!--ehcache 相关包 -->
383            <dependency>
384            <groupId>net.sf.ehcache</groupId>
385            <artifactId>ehcache</artifactId>
386            <version>2.7.5</version>
387        </dependency>
388        <dependency>
389            <groupId>com.googlecode.ehcache-spring-annotations</groupId>
390            <artifactId>ehcache-spring-annotations</artifactId>
391            <version>1.2.0</version>
392        </dependency>
393        
394         <dependency>
395             <groupId>com.google.zxing</groupId>
396             <artifactId>core</artifactId>
397             <version>3.0.0</version>
398         </dependency>
399         <dependency>
400             <groupId>com.google.zxing</groupId>
401             <artifactId>javase</artifactId>
402             <version>3.0.0</version>  
403         </dependency>
404    </dependencies>
405   <build>
406     <finalName>MaSSMyMy</finalName>
407   </build>
408 </project>
pom.xml

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:NIO(生活篇)

下一篇:初涉springboot(二)