struts2 Spring4 hiberante4 shiro2集成实例

技术:struts2,spring4,hibernate4,shiro2,h2database,jetty,easyui 1.36

功能:用户的CRUD,登陆,页面与后台权限验证,

使用maven 构建项目,下载代码后,运行start.bat或mvn jetty:run 一键启动项目。

 

 

 

 

 

1、UserLoginActioin.java

 

[java] view plaincopy在CODE上查看代码片派生到我的代码片

  1. package com.jst.myjstBase.web;  
  2.   
  3. public class UserLoginAction extends BaseAction<User> {  
  4.     /** 
  5.      *  
  6.      */  
  7.     private static final long serialVersionUID = 1L;  
  8.     private Log log = LogFactory.getLog(UserLoginAction.class);  
  9.     private User user;  
  10.     private String verifyCode;  
  11.       
  12.     public User getUser() {  
  13.         return user;  
  14.     }  
  15.   
  16.     public void setUser(User user) {  
  17.         this.user = user;  
  18.     }  
  19.   
  20.     public String getVerifyCode() {  
  21.         return verifyCode;  
  22.     }  
  23.   
  24.     public void setVerifyCode(String verifyCode) {  
  25.         this.verifyCode = verifyCode;  
  26.     }  
  27.   
  28.     public String login() throws Exception {  
  29.         // SecurityUtils.getSubject().login(new  
  30.         // UsernamePasswordToken(user.getUserCode(), user.getPassword()));  
  31.         try {  
  32.             if (request.getSession() != null && request.getSession().getAttribute("USERNAME") != null) {  
  33.                 return SUCCESS;  
  34.             }  
  35.             HttpSession session = request.getSession();  
  36.   
  37.             // 判断验证码  
  38.             if (verifyCode == null || !verifyCode.equals((String) session.getAttribute("verifyCode"))) {  
  39.                 addActionMessage("验证码错误");  
  40.                 log.debug("验证码错误");  
  41.                 return LOGIN;  
  42.             }  
  43.             // 清除验证码  
  44.             session.removeAttribute("verifyCode");  
  45.             // 判断用户名密码  
  46.             UsernamePasswordToken token = new UsernamePasswordToken(user.getUserCode(), user.getPassword());  
  47.             // UsernamePasswordToken token = new UsernamePasswordToken(  
  48.             // user.getUserCode(),EncryptUtils.encryptMD5(user.getPassword()));  
  49.             // token.setRememberMe(true);  
  50.             try {  
  51.                 currentUser.login(token);  
  52.                 session.setAttribute("USERNAME""admin");  
  53.             } catch (AuthenticationException e) {  
  54.                 log.error(e, e);  
  55.                 addActionMessage("用户名或密码错误");  
  56.                 return LOGIN;  
  57.             }  
  58.             return SUCCESS;  
  59.         } catch (Exception e) {  
  60.             log.error(e, e);  
  61.         }  
  62.         return LOGIN;  
  63.     }  
  64.   
  65. }<strong>  
  66. </strong>  


2、ShiroDbRealm.java

 

 

[java] view plaincopy在CODE上查看代码片派生到我的代码片

  1. package com.jst.common.service.impl;  
  2. public class ShiroDbRealm extends AuthorizingRealm {  
  3.     protected IUserService userService;  
  4.   
  5.     /** 
  6.      * 认证回调函数,登录时调用. 
  7.      */  
  8.     @Override  
  9.     protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {  
  10.         UsernamePasswordToken token = (UsernamePasswordToken) authcToken;  
  11.         User user = userService.findUserByLoginName(token.getUsername());  
  12.   
  13.         if (user != null) {  
  14.             byte[] salt = Encodes.decodeHex(user.getSalt());  
  15.             return new SimpleAuthenticationInfo(new ShiroUser(user.getId(), user.getUserCode(), user.getUserName()),  
  16.                     user.getPassword(), ByteSource.Util.bytes(salt), getName());  
  17.         }  
  18.         return null;  
  19.     }  
  20.   
  21.     /** 
  22.      * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用. 
  23.      */  
  24.     @Override  
  25.     protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {  
  26.         ShiroUser shiroUser = (ShiroUser) principals.getPrimaryPrincipal();  
  27. //      User user = userService.findUserByLoginName(shiroUser.loginName);  
  28.         SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();  
  29.         info.addRole("user");  
  30.         if(shiroUser.loginName.equals("admin")){  
  31.             info.addStringPermission("user:add");  
  32.             info.addStringPermission("user:edit");  
  33.             info.addStringPermission("user:update");  
  34.             info.addStringPermission("user:delete");  
  35.             info.addStringPermission("user:query");  
  36.         }else{  
  37.             info.addStringPermission("user:query");  
  38.         }  
  39.         // info.addRoles(user.getRoleList());  
  40.         return info;  
  41.     }  
  42. }  

3、applicationContext-shiro.xml

 

 

[html] view plaincopy在CODE上查看代码片派生到我的代码片

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  3.     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd"  
  4.     default-lazy-init="true">  
  5.   
  6.     <description>Shiro安全配置</description>  
  7.   
  8.     <!-- Shiro's main business-tier object for web-enabled applications -->  
  9.     <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">  
  10.         <property name="realm" ref="shiroDbRealm" />  
  11.         <property name="cacheManager" ref="shiroEhcacheManager" />  
  12.     </bean>  
  13.   
  14.     <!-- 項目自定义的Realm-->  
  15.     <bean id="shiroDbRealm" class="com.jst.common.service.impl.ShiroDbRealm">  
  16.         <property name="userService" ref="userServiceImpl"/>  
  17.     </bean>  
  18.       
  19.     <!-- Shiro Filter -->  
  20.     <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">  
  21.         <property name="securityManager" ref="securityManager" />  
  22.         <property name="loginUrl" value="/login.jsp" />  
  23.         <!-- <property name="successUrl" value="/" /> -->  
  24.         <property name="unauthorizedUrl" value="/error/noperms.jsp" />  
  25.         <property name="filterChainDefinitions">  
  26.             <value>  
  27.                 /logout = logout  
  28.                 /Images/** = anon  
  29.                 /system/verifyCode.action* = anon  
  30.                 /system/userLogin_login.action* = anon  
  31.                 /error/** = anon  
  32.                 /Json/** = anon  
  33.                 /Css/** = anon  
  34.                 /Js/** = anon  
  35.                 /admin/** = roles[admin]  
  36.                 /** = authc  
  37.             </value>  
  38.         </property>  
  39.     </bean>  
  40.       
  41.     <!-- 用户授权信息Cache, 采用EhCache -->  
  42.     <bean id="shiroEhcacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">  
  43.         <property name="cacheManagerConfigFile" value="classpath:ehcache/ehcache-shiro.xml"/>  
  44.     </bean>  
  45.       
  46.     <!-- 保证实现了Shiro内部lifecycle函数的bean执行 -->  
  47.     <!-- <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/> -->  
  48. </beans>  


4、UserList.jsp页面权限控制代码

 

 

[php] view plaincopy在CODE上查看代码片派生到我的代码片

  1. <div style="padding: 5px; height: auto">  
  2.    <shiro:hasPermission name="user:edit">  
  3. <span style="white-space:pre">    </span><a id="edit" href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-edit" plain="true">编辑</a>  
  4.    </shiro:hasPermission>  
  5.    <shiro:hasPermission name="user:delete">  
  6. <span style="white-space:pre">    </span><a id="delete" href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-remove" plain="true">删除</a>  
  7.    </shiro:hasPermission>  
  8. </div>   


5、BaseAction.java权限控制

 

 

[java] view plaincopy在CODE上查看代码片派生到我的代码片

  1. package com.jst.common.web;  
  2.   
  3.   
  4. public abstract class BaseAction<T> extends ActionSupport implements ServletRequestAware, ServletResponseAware {  
  5.     private final Log log = LogFactory.getLog(BaseAction.class);  
  6.   
  7.   
  8.     public abstract String getPremissionModelCode();  
  9.   
  10.     protected Subject currentUser;  
  11.   
  12.     // public abstract IBaseService<T> getBaseService();  
  13.     protected void setPages(Page<T> tmppage) {  
  14.         tmppage.setPageNo(page);  
  15.         tmppage.setPageSize(rows);  
  16.         tmppage.setOrder(order);  
  17.         tmppage.setOrderBy(sort);  
  18.     }  
  19.   
  20.     public BaseAction() {  
  21.         ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass();  
  22.         modelClass = (Class) pt.getActualTypeArguments()[0];  
  23.         currentUser = SecurityUtils.getSubject();  
  24.     }  
  25.   
  26.     /** 
  27.      * 继承BaseAction的action需要先设置这个方法,使其获得当前action的业务服务 
  28.      *  
  29.      * @param service 
  30.      */  
  31.     public void setService(IBaseService<T> baseService) {  
  32.         this.service = baseService;  
  33.     }  
  34.   
  35.     public String toAdd() throws Exception {  
  36.         if (currentUser.isPermitted(getPremissionModelCode() + ":add")) {  
  37.             return ADD;  
  38.         }  
  39.         WriterUtil.writerJson(response, "无权访问"+getPremissionModelCode() + ":add");  
  40.         return null;  
  41.     }  

 

7、登陆成功并返回index.jsp

源码:http://blog.csdn.net/javaee_ssh/article/details/42834949

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值