概述
登陆界面 login.jsp
login.jsp
<body>
<h1>登录页面----${message }</h1>
<img alt="" src="/static/img/1.jpg">
<form action="login.do" method="post">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit">
</form>
</body>
2.在tomcat容器启动时 会对web.xml的文件进行初始化,在web.xml我们会配个shiro过滤器来对请求进行过滤以及对权限认证文件的初始化
web.xml 的 shiro fliter如下
<!-- apache shiro权限 -->
<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>
</filter>
<filter-mapping>
<filter-name>shiroFilter</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>
3.applicationContext-shiro.xml 文件如下
<?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:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.zisine.service" />
<!-- 配置权限管理器 -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<!-- ref对应我们写的realm MyShiro -->
<property name="realm" ref="myShiro" />
<!-- 使用下面配置的缓存管理器 -->
<property name="cacheManager" ref="cacheManager" />
</bean>
<bean id="myShiro" class="com.zisine.service.MyShiro"></bean>
<!-- 配置shiro的过滤器工厂类,id- shiroFilter要和我们在web.xml中配置的过滤器一致 -->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<!-- 调用我们配置的权限管理器 -->
<property name="securityManager" ref="securityManager" />
<!-- 配置我们的登录请求地址 -->
<property name="loginUrl" value="/login.jsp" />
<!-- 配置我们在登录页登录成功后的跳转地址,如果你访问的是非/login地址,则跳到您访问的地址 -->
<property name="successUrl" value="/user.jsp" />
<!-- 如果您请求的资源不再您的权限范围,则跳转到/403请求地址 -->
<property name="unauthorizedUrl" value="/403.jsp" />
<!-- 权限配置 -->
<property name="filterChainDefinitions">
<value>
<!-- anon表示此地址不需要任何权限即可访问 -->
<!-- anon表示此地址不需要任何权限即可访问 -->
<!-- anon表示此地址不需要任何权限即可访问 -->
/login.do*=anon
/logout.do=anon
/loginn.do=anon
/login.jsp* = anon
/*.do* = authc
</value>
</property>
</bean>
<bean id="cacheManager" class="org.apache.shiro.cache.MemoryConstrainedCacheManager" />
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />
</beans>
4. 接下来我们只需要配置我们在配置文件里写的MyShrio.java
package com.zisine.service;
import java.util.Set;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.zisine.entity.Role;
import com.zisine.entity.User;
import com.zisine.util.EncryptUtils;
@Service
@Transactional
public class MyShiro extends AuthorizingRealm{
@Autowired
private UserService userServiceImpl;
//该方法的调用时机是前面有需要授权资源的请求时,比如前台验证某角色是否有改权限
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
// TODO Auto-generated method stub
String loginName=(String) arg0.fromRealm(getName()).iterator().next();
User user=userServiceImpl.findByName(loginName);
System.out.println("aaayanan");
System.out.println("users"+user.getUsername());
if(user!=null)
{
///用来存放所有查出来的角色和权限信息
SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
//用户的角色集合
info.setRoles(user.getRolesName());
System.out.println("useRoleNmae");
Set<Role> roleList=user.getUserRole();
for(Role role:roleList)
{
System.out.println("aa"+role.getRoleName());
info.addStringPermissions(role.getPermissionsName());
}
return info;
}
return null;
}
/*
*
* 登录认证
*///该方法的调用时机为controller层里面的login方法 shiro自动封装的登录方法就会跳到这个方法
@Override
protected AuthenticationInfo doGetAuthenticationInfo(
AuthenticationToken authcToken) throws AuthenticationException {
//获取基于用户名和密码的令牌
//实际上这个authcToken是从LoginController里面currentUser.login(token)传过来的
UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
//从数据库中查询用户用信息
User user = userServiceImpl.findByName(token.getUsername());
if (user != null) {
System.out.println("password"+user.getPassword());
//此处无需比对,比对的逻辑Shiro会做,我们只需返回一个和令牌相关的正确的验证信息
return new SimpleAuthenticationInfo(user.getUsername(), user
.getPassword(), getName());
} else {
//没有返回登录用户名对应的SimpleAuthenticationInfo对象时,就会在LoginController中抛出UnknownAccountException异常
return null;
}
}
5.接下来是controller层
@RequestMapping(value="/login",method=RequestMethod.POST)
public String login(User user,BindingResult bindingResult,RedirectAttributes redirectAttributes,ModelMap modelMap)
{
System.out.println("pass"+user.getPassword());
if(bindingResult.hasErrors())
return "login";
//使用权限工具进行用户登录 登录成功后跳到shiro配置成功的url里
//会自动绑定一个SecurityManager的线层 也就是在Myshiro文件里
try {
Subject currentUser = SecurityUtils.getSubject();
Session session=currentUser.getSession();
UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(),user.getPassword());
token.setRememberMe(true);
currentUser.login(token);
} catch (UnknownAccountException ex) {//用户名没有找到
System.out.println("用户名没有找到");
ExceptionUtil.printExceptionMsg( logger, ex );
ex.printStackTrace();
redirectAttributes.addFlashAttribute("message", "用户名没有找到");
return "redirect:/loginn.do";
} catch (IncorrectCredentialsException ex) {//用户名密码不匹配
System.out.println("用户名密码不匹配");
ex.printStackTrace();
redirectAttributes.addFlashAttribute("message", "用户名密码不匹配");
return "redirect:/loginn.do";
}catch (AuthenticationException e) {//其他的登录错误
System.out.println("其他的登录错误");
e.printStackTrace();
return "user.jsp";
}
System.out.println("123");
return "user.jsp";
}
6.前台验证权限
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>用户列表</title>
</head>
<body>
<h1>${message}</h1>
<h1>用户列表--<a href="add.do">添加用户</a>---<a href="logout.do">退出登录</a> </h1>
<h2>权限列表</h2>
<shiro:authenticated>登陆状态 :已经登陆</shiro:authenticated><br/>
<shiro:hasRole name="manager">认证身份:管理员</shiro:hasRole>
<shiro:hasRole name="admin">认证身份:超级管理员</shiro:hasRole>
<shiro:hasRole name="normal">认证身份:普通游客</shiro:hasRole>
<br/>
<shiro:hasAnyRoles name="manager,admin">**manager or admin 角色用户登录显示此内容**</shiro:hasAnyRoles>
<br/>当前用户名 :
<shiro:principal/>
<br>权限列表
<shiro:hasPermission name="add">add权限用户显示此内容<br></shiro:hasPermission>
<shiro:hasPermission name="select">select权限用户显示此内容<br></shiro:hasPermission>
<shiro:hasPermission name="update">update权限用户显示此内容<br></shiro:hasPermission>
<shiro:hasPermission name="user:query">query权限用户显示此内容<br/><shiro:principal/></shiro:hasPermission>
<shiro:lacksPermission name="delete"> 不具有user:del权限的用户显示此内容<br/> </shiro:lacksPermission>
<ul>
<c:forEach items="${userList }" var="user">
<li>用户名:${user.username }----密码:${user.password }----<a href="/user/edit/${user.id}">修改用户</a>----<a href="javascript:;" class="del" ref="${user.id }">删除用户</a></li>
</c:forEach>
</ul>
<img alt="" src="/static/img/1.jpg">
<script type="text/javascript" src="http://cdn.staticfile.org/jquery/1.9.1/jquery.min.js"></script>
<script>
$(function(){
$(".del").click(function(){
var id=$(this).attr("ref");
$.ajax({
type:"delete",
url:"/user/del/"+id,
success:function(e){
}
});
});
});
</script>
</body>
</html>
7.然后关于权限的五张表
一个用户可以有多种角色 一个角色可以属于多个用户 多对多
一个角色可以有多个权限 一个权限同样可以属于多个角色 多对多
所以有五张表 用户表(user.java)角色表(role.java) 用户角色表
权限表(permission.java)角色权限表
user.java
package com.zisine.entity;
import java.util.HashSet;
import java.util.Set;
public class User {
//用户id
private Integer id;
//用户名称
private String username;
//用户密码
private String password;
private Set<Role> userRole;
public Set<Role> getUserRole() {
return userRole;
}
public void setUserRole(Set<Role> userRole) {
this.userRole = userRole;
}
//一个用户他拥有多个脚色
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Set<String> getRolesName(){
Set<String> set=new HashSet<String>();
for (Role role : getUserRole()) {
set.add(role.getRoleName());
}
return set;
}
}
user.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.zisine.entity">
<!-- dynamic-insert="true":设置null字段在生成sql语句的时候不插入,避免了插入null值问题.但是为什么不起作用 (前台传到后台的是""不是null)-->
<class name="User" table="pl_user_t" dynamic-insert="true" dynamic-update="true">
<!-- id必须指定,name指定持久化标识符名称 -->
<id name="id" column="user_id">
<!-- native自动计算1值,如果是oracle的话将native改成sequence,然后在generator标记里添加:
<param name="sequence">sequence名称</param> -->
<generator class="native" />
</id>
<!-- javabean字段名与数据库表字段名映射,column不写的话默认表里的字段名与javabean的字段名一致 -->
<property name="username" column="user_name" />
<property name="password" column="password" />
<set name="userRole" table="role_user_t" lazy="false">
<key column="user_id"/>
<!-- key定义集合表到其拥有表的外键 -->
<many-to-many class="Role" column="role_id"/>
<!-- many-to-many 集合表到该元素的外键 -->
</set>
</class>
</hibernate-mapping>
role.java
package com.zisine.entity;
import java.beans.Transient;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class Role {
//角色ID
private Integer id;
//角色名称
private String roleName;
private Set<User> users;
private Set<Permission> permissions;
public Set<Permission> getPermissions() {
return permissions;
}
public void setPermissions(Set<Permission> permissions) {
this.permissions = permissions;
}
public Set<User> getUsers() {
return users;
}
public void setUsers(Set<User> users) {
this.users = users;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
@Transient
public List<String> getPermissionsName(){
List<String> list=new ArrayList<String>();
for (Permission per : getPermissions()) {
list.add(per.getPermissionName());
}
return list;
}
}
role.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.zisine.entity">
<!-- dynamic-insert="true":设置null字段在生成sql语句的时候不插入,避免了插入null值问题.但是为什么不起作用 (前台传到后台的是""不是null)-->
<class name="Role" table="pl_role_t" dynamic-insert="true" dynamic-update="true">
<!-- id必须指定,name指定持久化标识符名称 -->
<id name="id" column="role_id">
<!-- native自动计算值,如果是oracle的话将native改成sequence,然后在generator标记里添加:
<param name="sequence">sequence名称</param> -->
<generator class="native" />
</id>
<!-- javabean字段名与数据库表字段名映射,column不写的话默认表里的字段名与javabean的字段名一致 -->
<property name="roleName" column="role_name" />
<set name="users" table="role_user_t" inverse="false" lazy="false">
<key column="role_id"/>
<!-- key定义集合表到其拥有表的外键 -->
<many-to-many class="User" column="user_id"/>
<!-- many-to-many 集合表到该元素的外键 -->
</set>
<set name="permissions" table="role_permission_t" lazy="false">
<key column="role_id"/>
<!-- key定义集合表到其拥有表的外键 -->
<many-to-many class="com.zisine.entity.Permission" column="permission_id"/>
<!-- many-to-many 集合表到该元素的外键 -->
</set>
</class>
</hibernate-mapping>
permission.java
package com.zisine.entity;
import java.util.Set;
public class Permission {
private Integer id;
private String permissionName;
private Set<Role> roles;
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getPermissionName() {
return permissionName;
}
public void setPermissionName(String permissionName) {
this.permissionName = permissionName;
}
}
permission.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.zisine.entity">
<!-- dynamic-insert="true":设置null字段在生成sql语句的时候不插入,避免了插入null值问题.但是为什么不起作用 (前台传到后台的是""不是null)-->
<class name="Permission" table="pl_permission_t" dynamic-insert="true" dynamic-update="true">
<!-- id必须指定,name指定持久化标识符名称 -->
<id name="id" column="permission_id">
<!-- native自动计算值,如果是oracle的话将native改成sequence,然后在generator标记里添加:
<param name="sequence">sequence名称</param> -->
<generator class="native" />
</id>
<!-- javabean字段名与数据库表字段名映射,column不写的话默认表里的字段名与javabean的字段名一致 -->
<property name="permissionName" column="permission_name" />
<set name="roles" table="role_permission_t" inverse="false" lazy="false">
<key column="permission_id"/>
<!-- key定义集合表到其拥有表的外键 -->
<many-to-many class="Role" column="role_id"/>
<!-- many-to-many 集合表到该元素的外键 -->
</set>
</class>
</hibernate-mapping>
另外:如果项目用的是maven
早pom.xml配置
如下
<!--Apache Shiro所需的jar包-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-web</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.2.2</version>
</dependency>
如果没用的话 就去网上下即可
最后
以上就是文静大山为你收集整理的spring mvc +hibernate +spring +shiro 实现权限管理详细配置的全部内容,希望文章能够帮你解决spring mvc +hibernate +spring +shiro 实现权限管理详细配置所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复