`
knight_black_bob
  • 浏览: 858092 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

springmvc shiro

阅读更多

 

 

代码下载     http://download.csdn.net/download/knight_black_bob/9698729

 

 

代码已上传 ,

其中 springmvc +hibernate 封装的非常好用,大家可以学习下 

 

 

实例解析 :

首先访问 http://localhost:8083/springmvchibernate/web/user/showallusers

然后没有登陆 

http://localhost:8083/springmvchibernate/web/user/tologin

登陆过后

http://localhost:8083/springmvchibernate/web/user/showallusers

可以 访问 前提我是有 这个权限的

如果没有该权限 就进不去

 

 

 

 

 

@Entity
@Table(name = "t_user") 
public class User extends BaseEntity implements Serializable{

    /**
     * 
     */
    private static final long serialVersionUID = -1461963356403533227L;

    
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;

    @Column(name = "user_name")
    private String userName;
    
    @Column(name = "password")
    private String password;
    
    @Column(name = "tel")
    private String tel;
    
    @Column(name = "sex")
    private String sex;
     
    @Column(name = "description")
    private String description;

    
    
    @ManyToMany(cascade = CascadeType.PERSIST)  
    @JoinTable(name = "t_user_role", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id")) 
    private List<Role> roles;
    
    @Transient
    private long[] rightSum;
     
    
    
    public List<Role> getRoles() {
        return roles;
    }

    public void setRoles(List<Role> roles) {
        this.roles = roles;
    }

    public String getUserName() {
        return userName;
    }

    public String getPassword() {
        return password;
    }

    public String getTel() {
        return tel;
    }

    public String getSex() {
        return sex;
    }

    public String getDescription() {
        return description;
    }
 

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public void setTel(String tel) {
        this.tel = tel;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
 

    @Override
    public String toString() {
        return "User [id=" + id + ", userName=" + userName + ", password=" + password + ", tel="
                + tel + ", sex=" + sex + ", description=" + description + "]";
    }

   
    

    public void calculateRightSum() {
        int pos = 0;
        long code = 0;
        for(Role role: roles){
            if("-1".equals(role.getRoleValue())){ 
                roles = null;
                return;
            }
            for(Right right: role.getRights()){
                pos = right.getRightPos();
                code = right.getRightCode();
                
                rightSum[pos] = rightSum[pos] | code;
            }
        }
        
        roles = null;
        
    }
    
    public boolean hasRight(Right r){
        int pos = r.getRightPos();
        long code = r.getRightCode();
        
        return !((rightSum[pos] & code) == 0);
    }
    
    
}

 

@Entity
@Table(name = "t_role")  
public class Role extends BaseEntity implements Serializable{

    /**
     * 
     */
    private static final long serialVersionUID = -3249248953909188737L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id; 
    
    @Column(name = "role_name")
    private String roleName;  
    
    @Column(name = "role_value")
    private String roleValue;  
    
    @Column(name = "role_desc")
    private String roleDesc; 
    
    @ManyToMany(mappedBy = "roles")
    @Basic(fetch = FetchType.LAZY)
    private List<User> users; 
    
    @ManyToMany(cascade={CascadeType.PERSIST,CascadeType.REFRESH,CascadeType.MERGE}, fetch = FetchType.LAZY)  
    @JoinTable(name = "t_role_right", joinColumns = @JoinColumn(name = "role_id"), inverseJoinColumns = @JoinColumn(name = "right_id")) 
    private List<Right> rights;

    
    

   public List<User> getUsers() {
        return users;
    }


    public void setUsers(List<User> users) {
        this.users = users;
    } 


    public int getId() {
        return id;
    }


    public String getRoleName() {
        return roleName;
    }


    public String getRoleValue() {
        return roleValue;
    }


    public String getRoleDesc() {
        return roleDesc;
    }


    public List<Right> getRights() {
        return rights;
    }


    public void setId(int id) {
        this.id = id;
    }


    public void setRoleName(String roleName) {
        this.roleName = roleName;
    }


    public void setRoleValue(String roleValue) {
        this.roleValue = roleValue;
    }


    public void setRoleDesc(String roleDesc) {
        this.roleDesc = roleDesc;
    }


    public void setRights(List<Right> rights) {
        this.rights = rights;
    }


    @Override
    public String toString() {
        return "Role [id=" + id + ", roleName=" + roleName + ", roleValue=" + roleValue
                + ", roleDesc=" + roleDesc + "]";
    }
     
    
}

 

@Entity
@Table(name = "t_right")
public class Right extends BaseEntity implements Serializable{

    /**
     * 
     */
    private static final long serialVersionUID = 1444825234975317847L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;  
    
    @Column(name = "right_name")
    private String rightName =  "";
    
    @Column(name = "right_url")
    private String rightUrl;  
    
    @Column(name = "right_desc")
    private String rightDesc;  
    
    @Column(name = "right_code")
    private long rightCode;   
    
    @Column(name = "right_pos")
    private int rightPos;    
    
    @Column(name = "common")
    private boolean common ;

     @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "rights")
    private List<Role> roles;

    
    
    public List<Role> getRoles() {
        return roles;
    }

    public void setRoles(List<Role> roles) {
        this.roles = roles;
    } 

    public int getId() {
        return id;
    }

    public String getRightName() {
        return rightName;
    }

    public String getRightUrl() {
        return rightUrl;
    }

    public String getRightDesc() {
        return rightDesc;
    }

    public long getRightCode() {
        return rightCode;
    }

    public int getRightPos() {
        return rightPos;
    }

    public boolean isCommon() {
        return common;
    }

    public void setId(int id) {
        this.id = id;
    }

    public void setRightName(String rightName) {
        this.rightName = rightName;
    }

    public void setRightUrl(String rightUrl) {
        this.rightUrl = rightUrl;
    }

    public void setRightDesc(String rightDesc) {
        this.rightDesc = rightDesc;
    }

    public void setRightCode(long rightCode) {
        this.rightCode = rightCode;
    }

    public void setRightPos(int rightPos) {
        this.rightPos = rightPos;
    }

    public void setCommon(boolean common) {
        this.common = common;
    }

    @Override
    public String toString() {
        return "Right [id=" + id + ", rightName=" + rightName + ", rightUrl=" + rightUrl
                + ", rightDesc=" + rightDesc + ", rightCode=" + rightCode + ", rightPos=" + rightPos
                + ", common=" + common + "]";
    }
    
    
    
}

 

@Controller
@RequestMapping("/web/user")
public class UserAciton extends BaseAction { 
    
    protected static final Logger logger = LoggerFactory.getLogger(UserAciton.class);
    
    @Resource
    private UserService userService;
    
  
    
    
    @RequestMapping(value = "/tologin")
    public String toLogin(HttpServletRequest request){
        logger.debug("================");
        return "/web/user/login";
    }
    
    @RequestMapping(value = "/login" ,method=RequestMethod.POST)
    public String login(User currUser,HttpServletRequest request){
        logger.debug("======login==========");
//        String code = (String) session.getAttribute("validateCode");
//        String submitCode = WebUtils.getCleanParam(request, "validateCode");
        
        Subject user = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(currUser.getUserName(),currUser.getPassword());
        token.setRememberMe(true);
        try {
            user.login(token);
            logger.debug("======login success==========");
            return "/web/user/new";
        }catch (AuthenticationException e) {
            token.clear();
            logger.debug("======login error==========");
            return "/web/user/tologin";
        }
        
    }
    
    
    @RequestMapping(value = "/new")
    public String newForm(HttpServletRequest request){
        logger.debug("================");
        return "/web/user/new";
    }

    @RequestMapping(value = "/showallusers")
    public String showAllUsers(HttpServletRequest request){
        logger.debug("================");
        Subject currentUser = SecurityUtils.getSubject();
        if(currentUser.isPermitted("/web/user/showallusers")){
            return "/web/user/showallusers";
        }else{
            return "/web/user/new";
        }  
    }
    
    
    
    @Transactional
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public void add(User user,HttpServletRequest request){
        logger.debug("================"+user.toString());
        //userService.save(user);
        logger.debug("================");
    }
     
    @RequestMapping(value = "/test")
    public String test(HttpServletRequest request){
        User user = new User();
        user.setPassword("123456");
        user.setSex("1");
        user.setTel("15010666051");
        user.setUserName("包优");
        user.setDescription("test");
        //userService.save(user);
        logger.debug("================");
        return "/web/user/new";
    }
    
}

 

@Service
public class SysRealm  extends AuthorizingRealm  implements InitializingBean{

    public static Map<String,Right> map = new HashMap<String,Right>();
    
   @Resource
    UserService userService;
   
   @Resource
   RightService rightService;
   @Resource
   RoleService roleService;
    

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        
        String userName = (String)super.getAvailablePrincipal(principals); 
       List<String> roleList = new ArrayList<String>();
      List<String> permissionList = new ArrayList<String>();
      //从数据库中获取当前登录用户的详细信息
      User user = userService.find("userName", userName);
      if(null != user){
          //实体类User中包含有用户角色的实体类信息
          if(null!=user.getRoles() && user.getRoles().size()>0){
              //获取当前登录用户的角色
              for(Role role : user.getRoles()){
                  roleList.add(role.getRoleName());
                  //实体类Role中包含有角色权限的实体类信息
                   if(null!=role.getRights() && role.getRights().size()>0){
                      //获取权限
                      for(Right right : role.getRights()){
                          if(!StringUtils.isEmpty(right.getRightUrl())){
                              permissionList.add(right.getRightUrl());
                          }
                      }
                  } 
                 /*List<Right>  rights= rightService.findByRoleId(role.getId());
                 if(null!=rights && rights.size()>0){
                     //获取权限
                     for(Right right : role.getRights()){
                         if(!StringUtils.isEmpty(right.getRightUrl())){
                             permissionList.add(right.getRightUrl());
                         }
                     }
                 }*/
              }
          }
      }else{
          
      }
      //为当前用户设置角色和权限
      SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo();
      simpleAuthorInfo.addRoles(roleList);
      simpleAuthorInfo.addStringPermissions(permissionList);
      return simpleAuthorInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
            throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
        User user = userService.find("userName", token.getUsername());
        if (user != null) {
            return new SimpleAuthenticationInfo(user.getUserName(), user
                    .getPassword(), user.getUserName());
        } else {
            return null;
        }
    }

    
    @Override
    public void afterPropertiesSet() throws Exception {
        
        
    }

   

}

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:cache="http://www.springframework.org/schema/cache"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee"
	xmlns:jms="http://www.springframework.org/schema/jms" xmlns:lang="http://www.springframework.org/schema/lang"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:oxm="http://www.springframework.org/schema/oxm"
	xmlns:p="http://www.springframework.org/schema/p" xmlns:task="http://www.springframework.org/schema/task"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="
	http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
    http://www.springframework.org/schema/tool http://www.springframework.org/schema/tool/spring-tool.xsd
    http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
    http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
    http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms.xsd
    http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
    http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm.xsd
    http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"
	default-autowire="byName"> 
 
  
 
    
 
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
		<property name="realm" ref="sysRealm" />
	</bean>
	 
	<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
		<property name="securityManager" ref="securityManager" />
		<property name="loginUrl" value="/web/user/tologin" />
		<property name="successUrl" value="/web/user/tologin" />
		<property name="unauthorizedUrl" value="/web/user/error" />
		<property name="filterChainDefinitions">
			<value> 
			    /web/user/error = anon
			    /web/user/new = anon
			    /web/user/tologin = anon
				/web/user/login = anon
				/web/** = authc
			</value>
		</property>
	</bean>
	 
	<!-- <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor" />
	  <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
		<property name="securityManager" ref="securityManager" />
	</bean>  
	<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" /> 
	 -->
	 
</beans>

 

 打开 注释,就可以使用注解的方式 进行拦截,不用 url 去 一个个 匹配了

 @RequiresPermissions(value = { "/web/user/showallusers" })   
 <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor" />  
      <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">  
        <property name="securityManager" ref="securityManager" />  
    </bean>    
    <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />   

 

 

 

<filter>  
        <filter-name>shiroFilter</filter-name>  
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>  
        <init-param>  
            <param-name>targetFilterLifecycle</param-name>  
            <param-value>true</param-value>  
        </init-param> 
        <load-on-startup>3</load-on-startup> 
    </filter>  
  
    <filter-mapping>  
        <filter-name>shiroFilter</filter-name>  
        <servlet-name>springmvc</servlet-name>  
    </filter-mapping>   

 

 

 

 

 

 

 

 

 

 

 

 

 

捐助开发者

在兴趣的驱动下,写一个免费的东西,有欣喜,也还有汗水,希望你喜欢我的作品,同时也能支持一下。 当然,有钱捧个钱场(右上角的爱心标志,支持支付宝和PayPal捐助),没钱捧个人场,谢谢各位。



 
 
 谢谢您的赞助,我会做的更好!

 

 

 

 

 

 

0
0
分享到:
评论

相关推荐

    cas结合 springmvc shiro 单点登录

    本项目是关于如何将CAS(Central Authentication Service)与SpringMVC和Shiro结合实现SSO的实践示例。 首先,我们来了解一下三个主要组件: 1. **CAS**: CAS是一个开源的身份验证框架,主要用于处理用户身份验证...

    springMVC shiro 认证-授权 结合示例

    本demo 采用的shirodemo 演变而来(第3个连接): 1、其中添加了与数据库交互,数据分布设置的是用户-权限-资源 2、添加了验证码验证 3、纠正了无权限跳转BUG 4、添加了shiro 页面标签使用示例(sysResourceList/...

    cas.zip_cas 结合 springmvc shiro 做项目单点认证

    本项目结合了CAS(Central Authentication Service)、SpringMVC和Shiro三个核心组件来实现这样的功能。 CAS是一个开源的身份验证框架,它提供了基于Web的SSO解决方案。CAS服务器作为认证中心,负责验证用户的凭证...

    spring+springMVC+shiro 完美例子

    源代码中,你可能会发现SpringMVC的Controller如何调用Shiro进行认证和授权,以及如何配置Shiro的配置文件(如shiro.ini或Java配置类),以实现定制化的安全策略。 总之,这个"spring+springMVC+shiro 完美例子"是...

    springmvc+shiro 实现安全登录的demo

    实现了shiro安全登录,包括密码加密匹配和登录失败次数限制的功能

    springmvc+spring+shiro+cas单点登录实例

    spring+springmvc+shiro+cas单点登录实例 springmvc+spring+shiro+cas单点登录实例 加入了登录验证码认证,修改了下首页样式,不过样式没有弄好,很丑的,有空自己再弄下 说明:cas-server是单点登录服务端,用的是...

    springmvc+shiro+mybaits+mysql

    标题 "springmvc+shiro+mybaits+mysql" 暗示了这是一个基于Spring MVC、Apache Shiro、MyBatis以及MySQL数据库构建的权限管理系统的实现。下面将详细阐述这些技术栈及其在系统中的作用。 Spring MVC是Spring框架的...

    SpringMVC+Shiro+Redis

    使用SpringMVC、Shiro、Redis写的小demo, 配置: JDK 1.7+; MySql 5.+; Maven3.+; spring:4.1.7.RELEASE; shiro:1.2.5; mybatis:3.3.0; druid:1.0.25;redis:2.8.0; - - - - - - 神奇传送阵( ﹁ ﹁ ) ~→...

    SPRINGMVC+SHIRO+MYSQL

    **一、SpringMVC框架** SpringMVC是Spring框架的一个模块,主要用于构建Web应用程序。它采用Model-View-Controller(MVC)设计模式,将业务逻辑、数据处理和用户界面分离,提高了代码的可维护性和可测试性。...

    springmvc整合shiro

    而Apache Shiro是一个轻量级的安全框架,主要负责身份验证、授权(权限控制)、会话管理和加密。本文将深入探讨如何将Spring MVC与Shiro整合,实现LDAP(轻量目录访问协议)认证和简单的时间权限管理。 **1. Spring...

    springMVC+shiro实现动态权限验证.zip

    springMVC+shiro实现动态权限验证,实现动态设置用户角色,根据角色来决定哪些url可以访问 抱歉了各位需要修改下配置文件(org.eclipse.wst.common.component) &lt;?xml version="1.0" encoding="UTF-8"?&gt; ...

    基于SSM框架简单的后台权限管理系统整合spring springmvc shiro mybatis easy.zip

    重点:所有项目都有sql文件,比其他博主项目要严谨一万倍所有项目本人亲自测试可运行使用!!有任何问题私我解决! 1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私...

    SpringMVC整合Shiro的完整示例代码下载

    在本文中,我们将深入探讨如何将SpringMVC与Apache Shiro框架整合,以实现一个安全的Web应用程序。这个示例代码提供了完整的实现过程,让你能够快速理解和应用到自己的项目中。 首先,SpringMVC是Spring框架的一个...

    Guns基于SpringBoot 2致力于做更简洁的后台管理系统完美整合springmvc shiro myba.zip

    重点:所有项目都有sql文件,比其他博主项目要严谨一万倍所有项目本人亲自测试可运行使用!!有任何问题私我解决! 1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私...

    SpringMVC shiro源码

    SpringMVC 和 Apache Shiro 是两个在 Java Web 开发中常用的框架,它们分别负责不同的职责。SpringMVC 是一个强大的 MVC(Model-View-Controller)框架,主要用于处理 Web 应用的请求、业务逻辑和视图展示。而 ...

    SpringMVC+shiro权限管理

    **SpringMVC+Shiro权限管理** 在现代Web应用程序开发中,权限管理和用户认证是至关重要的组成部分。SpringMVC和Apache Shiro都是Java领域中广泛使用的框架,它们各自在不同的层面上提供了强大的功能。SpringMVC是...

    Springboot+Mybatis-plus+ SpringMvc+Shiro+Redis企业级报表后台管理系统.rar

    项目描述 在上家公司自己集成的一套系统,用了两个多月的时间完成的:Springboot+Mybatis-plus+ SpringMvc+Shiro+Redis企业级开发系统 Springboot作为容器,使用mybatis作为持久层框架 使用官方推荐的thymeleaf做为...

    Guns基于SpringBoot致力于做更简洁的后台管理系统完美整合springmvc shiro 分页插件Page.zip

    重点:所有项目都有sql文件,比其他博主项目要严谨一万倍所有项目本人亲自测试可运行使用!!有任何问题私我解决! 1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私...

    springmvc shiro框架

    SpringMVC 和 Apache Shiro 是两个在 Java Web 开发中常用的框架。SpringMVC 是一个 Model-View-Controller 模式的轻量级框架,用于处理应用程序的请求分发和视图渲染;而 Apache Shiro 是一个强大且易用的安全管理...

Global site tag (gtag.js) - Google Analytics