shiro:自定义remle(二)
SpringMVC+SpringMVC+Mybatis项目
1:导入相关依赖
<dependencies>
<!--测试依赖-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!--数据库驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!-- 数据库连接池 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<!-- 数据库连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.22</version>
</dependency>
<!--Mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.2</version>
</dependency>
<!--spring 数据源配置-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.10</version>
</dependency>
<!--AOP的jar包-->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>
<!--Spring依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<!--shiro核心包依赖-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.4.0</version>
</dependency>
<!--shiro web包依赖-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-web</artifactId>
<version>1.4.0</version>
</dependency>
</dependencies>
<!--maven 静态资源管理,主要是为了导出mapper-->
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
<include>**/*.ini</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
<include>**/*.ini</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
2:数据库建表语句
/*用户表*/
CREATE TABLE `t_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(20) NOT NULL,
`password` varchar(100) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `username` (`username`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
INSERT INTO `t_user` VALUES ('1', 'songsong', '123');
INSERT INTO `t_user` VALUES ('2', 'yuanhang', '456');
/*角色表*/
CREATE TABLE `t_role` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`role_name` varchar(50) NOT NULL,
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `role_name` (`role_name`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
INSERT INTO `t_role` VALUES ('1', 'banzhang', '2019-10-10 00:00:00');
INSERT INTO `t_role` VALUES ('2', 'student', '2019-10-09 00:00:00');
/*权限表*/
CREATE TABLE `t_permission` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`permission_name` varchar(50) NOT NULL,
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `permission_name` (`permission_name`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
INSERT INTO `t_permission` VALUES ('1', 'student:yq', '2019-10-09 00:00:00');
INSERT INTO `t_permission` VALUES ('2', 'student:study', '2019-10-09 00:00:00');
/*用户 角色关联表*/
CREATE TABLE `t_user_role` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) DEFAULT NULL,
`role_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `user_id` (`user_id`,`role_id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
INSERT INTO `t_user_role` VALUES ('1', '1', '1');
INSERT INTO `t_user_role` VALUES ('3', '1', '2');
INSERT INTO `t_user_role` VALUES ('2', '2', '2');
/*角色 权限关联表*/
CREATE TABLE `t_role_permission` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`permission_id` int(11) DEFAULT NULL,
`role_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `permission_id` (`permission_id`,`role_id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
INSERT INTO `t_role_permission` VALUES ('1', '1', '1');
INSERT INTO `t_role_permission` VALUES ('2', '2', '1');
INSERT INTO `t_role_permission` VALUES ('3', '2', '2');
3:构建javaben对象
com\shiro\vo\UserVo.java
package com.shiro.vo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserVo {
//用户id
private Integer id;
//用户名称
private String username;
//用户密码
private String password;
}
com\shiro\vo\RoleVo.java
package com.shiro.vo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class RoleVo {
//角色id
private Integer id;
//角色名称
private String roleName;
//创建时间
private Date createTime;
}
com\shiro\vo\PermissionVo.java
package com.shiro.vo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class PermissionVo {
//权限id
private Integer id;
//权限名称
private String permissionName;
//创建时间
private Date createTime;
}
4:构建mapper接口以及配置文件
查询用户mapper:com\shiro\mapper\UserMapper.java
package com.shiro.mapper;
import com.shiro.vo.UserVo;
import org.apache.ibatis.annotations.Param;
public interface UserMapper {
//通过用户名查询用户信息
public UserVo queryUserByUsername(@Param("username") String username);
}
查询用户配置文件:com\shiro\mapper\UserMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.shiro.mapper.UserMapper">
<select id="queryUserByUsername" parameterType="string" resultType="UserVo">
select * from t_user where username = #{username}
</select>
</mapper>
查询角色mapper:com\shiro\mapper\RoleMapper.java
package com.shiro.mapper;
import org.apache.ibatis.annotations.Param;
import java.util.Set;
public interface RoleMapper {
//通过用户名查询角色
public Set<String> queryAllRoleNameByUsername(@Param("username") String username);
}
查询角色配置文件:com\shiro\mapper\RoleMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.shiro.mapper.RoleMapper">
<select id="queryAllRoleNameByUsername" parameterType="string" resultType="string">
SELECT t_role.role_name FROM t_user
INNER JOIN t_user_role on t_user.id = t_user_role.user_id
INNER JOIN t_role on t_role.id = t_user_role.role_id
where t_user.username = #{username}
</select>
</mapper>
查询权限mapper:com\shiro\mapper\PermissionMapper.java
package com.shiro.mapper;
import org.apache.ibatis.annotations.Param;
import java.util.Set;
public interface PermissionMapper {
//通过用户名查询权限
public Set<String> queryAllPermissionByUsername(@Param("username") String username);
}
查询权限配置文件:com\shiro\mapper\PermissionMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.shiro.mapper.PermissionMapper">
<select id="queryAllPermissionByUsername" parameterType="string" resultType="string">
SELECT DISTINCT t_permission.permission_name FROM t_user
INNER JOIN t_user_role on t_user.id = t_user_role.user_id
INNER JOIN t_role on t_role.id = t_user_role.role_id
INNER JOIN t_role_permission on t_role_permission.role_id = t_role.id
INNER JOIN t_permission on t_permission.id = t_role_permission.permission_id
where t_user.username = #{username}
</select>
</mapper>
5:构建数据库连接文件
resources\jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://ip:3306/my_test?useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=xxxxxxx
6:构建mybatis配置文件
resources\mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<!--打印sql语句-->
<setting name="logImpl" value="STDOUT_LOGGING" />
<!-- 全局性设置懒加载 -->
<setting name="lazyLoadingEnabled" value="true"/>
<!-- 每个属性都按需加载 -->
<setting name="aggressiveLazyLoading" value="false"/>
<!-- 开启驼峰命名 -->
<setting name="mapUnderscoreToCamelCase" value="true" />
</settings>
<!--开启别名-->
<typeAliases>
<package name="com.shiro.vo" />
</typeAliases>
<!--mapper文件-->
<mappers>
<mapper resource="com/shiro/mapper/UserMapper.xml" />
<mapper resource="com/shiro/mapper/RoleMapper.xml" />
<mapper resource="com/shiro/mapper/PermissionMapper.xml" />
</mappers>
</configuration>
7:构建dao层配置文件
resources\spring-mapper.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--加载jdbc配置文件-->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:jdbc.properties</value>
</list>
</property>
</bean>
<!--数据源配置 数据源提供者包括:spring、c3p0、dbcp、druid-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!--配置得到SqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<!--绑定mybatis配置文件-->
<property name="configLocation" value="classpath:mybatis-config.xml"></property>
</bean>
<!--通过MapperScannerConfigurer配置dao接口扫描包 实现动态注入到spring容器中-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--注入sqlSessionFactory-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
<!--要扫描的dao包-->
<property name="basePackage" value="com.shiro.mapper" />
</bean>
</beans>
8:构建service接口以及实现类
接口:com\shiro\service\UserService.java
package com.shiro.service;
import com.shiro.vo.UserVo;
import java.util.Set;
public interface UserService {
/*查询用户*/
public UserVo queryUserByUsername(String username);
/*查询角色*/
public Set<String> queryAllRoleNameByUsername(String username);
/*查询权限*/
public Set<String> queryAllPermissionByUsername(String username);
}
实现类:com\shiro\service\impl\UserServiceImpl.java
package com.shiro.service.impl;
import com.shiro.mapper.PermissionMapper;
import com.shiro.mapper.RoleMapper;
import com.shiro.mapper.UserMapper;
import com.shiro.service.UserService;
import com.shiro.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Set;
@Service
public class UserServiceImpl implements UserService {
@Autowired
UserMapper userMapper;
@Autowired
RoleMapper roleMapper;
@Autowired
PermissionMapper permissionMapper;
public UserVo queryUserByUsername(String username) {
return this.userMapper.queryUserByUsername(username);
}
public Set<String> queryAllRoleNameByUsername(String username) {
return this.roleMapper.queryAllRoleNameByUsername(username);
}
public Set<String> queryAllPermissionByUsername(String username) {
return permissionMapper.queryAllPermissionByUsername(username);
}
}
9:构建service层配置文件
resources\spring-service.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:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--注解版扫描包,这个包下面的注解就会生效-->
<context:component-scan base-package="com.shiro.service" />
<!--配置事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--配置事务通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<!--给哪些方法配置事务-->
<tx:attributes>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!--配置事务切入-->
<aop:config>
<aop:pointcut id="txpoint" expression="execution(* com.shiro.mapper.*.*(..))"></aop:pointcut>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txpoint"></aop:advisor>
</aop:config>
</beans>
10:构建controller控制类
com\shiro\controller\LoginController.java
package com.shiro.controller;
import com.shiro.vo.UserVo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/user")
public class LoginController {
/*跳转登录界面*/
@GetMapping("/login")
public String login(){
System.out.println("goto login page");
return "login";
}
/*登录请求*/
@PostMapping("/login")
public String loginLogic(UserVo userVo){
System.out.println("login logic");
//获取subject
Subject subject = SecurityUtils.getSubject();
//获取令牌
UsernamePasswordToken token = new UsernamePasswordToken(userVo.getUsername(), userVo.getPassword());
//自动调用自定义的realm进行身份认证
subject.login(token);
System.out.println("登录状态为:" + subject.getPrincipal());
return "login"; //登录成功
}
/*无权限页面,通过shiro.ini进行跳转*/
@GetMapping("/error")
public String userError(){
System.out.println("没有权限访问的跳转页面");
return "user_error";
}
}
11:构建controller层配置文件
resources\springmvc-servlet.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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 自动扫描包,让指定包下的注解生效,由IOC容器统一管理 -->
<context:component-scan base-package="com.shiro.controller"/>
<!-- 让Spring MVC不处理静态资源 -->
<mvc:default-servlet-handler />
<!--annotation-driven配置帮助我们完成处理器映射器和处理器适配器-->
<mvc:annotation-driven />
<!--视图解析器:DispatcherServlet给他的ModelAndView-->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--前缀-->
<property name="prefix" value="/WEB-INF/jsp/"/>
<!--后缀-->
<property name="suffix" value=".jsp"/>
</bean>
</beans>
12:构建Spring总配置文件
resources\applicationContext.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="spring-mapper.xml"/>
<import resource="spring-service.xml"/>
<import resource="springmvc-servlet.xml"/>
</beans>
13:构建自定义shiro的Realm
com\shiro\realm\MyRealm.java
package com.shiro.realm;
import com.shiro.service.UserService;
import com.shiro.vo.UserVo;
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.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;
import org.springframework.web.context.ContextLoader;
import java.util.Set;
@Component
/*自定义realm*/
public class MyRealm extends AuthorizingRealm {
/*查询权限信息
* 触发:请求触发:/user/query = roles["admin"]
* /user/insert = perms["user:insert"] <shiro:hasRole <shiro:hasPermission
* 查询方式:通过用户名查询角色 权限信息
* */
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
//获取用户登录时发送过来的用户名
String username = principalCollection.getPrimaryPrincipal().toString();
//查询用户权限(DB)
UserService userServiceImpl = ContextLoader.getCurrentWebApplicationContext().getBean("userServiceImpl", UserService.class);
Set<String> roles = userServiceImpl.queryAllRoleNameByUsername(username);
Set<String> perms = userServiceImpl.queryAllPermissionByUsername(username);
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roles);
info.setStringPermissions(perms);
return info;
}
/*查询身份信息
* 触发:subject.login(token)
* */
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
//获取用户登录时发送过来的用户名
String username = token.getPrincipal().toString();
//查询用户信息(DB)
UserService userServiceImpl = ContextLoader.getCurrentWebApplicationContext().getBean("userServiceImpl", UserService.class);
UserVo userVo = userServiceImpl.queryUserByUsername(username);
if(userVo==null){
return null;
}
return new SimpleAuthenticationInfo(userVo.getUsername(), userVo.getPassword(),this.getName());
}
}
14:构建shiro配置文件
resources\shiro.ini
[main]
#没有身份认证时的跳转地址(自定义)
shiro.loginUrl= /user/login
#角色权限校验不通过时的跳转地址
shiro.unauthorizedUrl = /user/error
#登出后的跳转地址
shiro.redirectUrl = /user/login
#声明自定义realm
realm = com.shiro.realm.MyRealm
#注册安装自定义realm
securityManager.realms=$realm
[urls]
#不拦截
/user/login = anon
/getuser = anon
/getrole = anon
#删除用户 要登录而且角色必须是管理员和经理
/user/delUser = authc,roles["admin","manager"]
#查询用户 要登录而且必须有user:query的权限
/user/getallUsers = authc
#登出
/user/logout = logout
15:配置web.xml配置spring及shiro加载项
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!--
在启动时初始化shiro环境 将securityManager托管到SecurityUtils工具类中
-->
<filter>
<filter-name>shiroFilter</filter-name>
<filter-class>org.apache.shiro.web.servlet.ShiroFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>shiroFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--加载shiro.ini默认配置-->
<listener>
<listener-class>org.apache.shiro.web.env.EnvironmentLoaderListener</listener-class>
</listener>
<!--1.注册DispatcherServlet-->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--关联一个springmvc的配置文件:【servlet-name】-servlet.xml-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</init-param>
<!--启动级别-1-->
<load-on-startup>1</load-on-startup>
</servlet>
<!--/ 匹配所有的请求;(不包括.jsp)-->
<!--/* 匹配所有的请求;(包括.jsp)-->
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--启动Web容器时,初始化spring配置,可以让自定义realm拿到bean-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
</web-app>
16:构建相关界面
WEB-INF\jsp\login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<shiro:guest>
欢迎您 游客~~~
</shiro:guest>
<br />
<shiro:notAuthenticated>
请登录:
<form action="/user/login" method="post">
username:<input type="text" name="username"><br />
password:<input type="text" name="password"><br />
<button type="submit">登录</button>
</form>
</shiro:notAuthenticated>
<br />
<shiro:authenticated>
你已经登录 欢迎你:<shiro:principal /> <a href="/user/logout">退出</a>
<br />
<%--角色是banzhang或者student--%>
<shiro:hasAnyRoles name="banzhang,student">
都要学习【songsong、yuanhang】
</shiro:hasAnyRoles>
<br />
<%--角色是student的--%>
<shiro:hasRole name="student">
我是学生【songsong、yuanhang】
</shiro:hasRole>
<br />
<%--角色不是banzhang的--%>
<shiro:lacksRole name="banzhang">
我不是班长【yuanhang】
</shiro:lacksRole>
<br />
<%--角色是banzhang的--%>
<shiro:hasRole name="banzhang">
我是班长【songsong】
</shiro:hasRole>
<br />
<%--权限包含student:yq--%>
<shiro:hasPermission name="student:yq">
我有收钱的权限【songsong】
</shiro:hasPermission>
<br />
<%--权限不包含student:yq的--%>
<shiro:lacksPermission name="student:yq">
我没有收钱的权限【yuanhang】
</shiro:lacksPermission>
</shiro:authenticated>
</body>
</html>
WEB-INF\jsp\user_error.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
权限不足
</body>
</html>
17:访问测试
shiro:自定义remle(二)的更多相关文章
- Shiro笔记(二)身份验证
Shiro笔记(二)身份验证 一.核心代码 @Test public void helloWorldTest(){ IniSecurityManagerFactory factory = new In ...
- Shiro 自定义登陆、授权、拦截器
Shiro 登陆.授权.拦截 按钮权限控制 一.目标 Maven+Spring+shiro 自定义登陆.授权 自定义拦截器 加载数据库资源构建拦截链 使用总结: 1.需要设计的数据库:用户.角色.权限 ...
- 解决shiro自定义filter后,ajax登录无法登录,并且无法显示静态资源的问题
这个问题困扰了我一天,看了下面两个文章,豁然开朗: https://www.cnblogs.com/gj1990/p/8057348.html https://412887952-qq-com.ite ...
- Android自定义视图二:如何绘制内容
这个系列是老外写的,干货!翻译出来一起学习.如有不妥,不吝赐教! Android自定义视图一:扩展现有的视图,添加新的XML属性 Android自定义视图二:如何绘制内容 Android自定义视图三: ...
- PHP自定义生成二维码跳转地址
比较简单的一款PHP自定义生成二维码跳转地址,手机端微信扫码,自动跳转到定义好的链接.支持自定义生成二维码尺寸.间距等. 鼠标悬浮显示二维码弹出层,离开后消失.js实现,代码如下: $(fu ...
- vue2.0 自定义 生成二维码(QRCode)组件
1.自定义 生成二维码组件 QRCode.vue <!-- 生成二维码 组件 --> <template> <canvas class="qrcode-canv ...
- Apcahe Shiro学习笔记(二):通过JDBC进行权限控制
一.概述: 官方对Realm(领域)的描述:https://www.infoq.com/articles/apache-shiro 其功能本质上是一个安全特定的DAO,用于链接数据持久层(任何形式的都 ...
- shiro基础学习(二)—shiro认证
一.shiro简介 shiro是apache旗下一个开源框架,它将软件系统的安全认证相关的功能抽取出来,实现用户身份认证.权限授权.加密.会话管理等功能,组成了一个通用的安全认证框架. 以下 ...
- Shiro自定义realm实现密码验证及登录、密码加密注册、修改密码的验证
一:先从登录开始,直接看代码 @RequestMapping(value="dologin",method = {RequestMethod.GET, RequestMethod. ...
随机推荐
- war 和 war exploded
IDEA 开发项目时,部署 tomcat 的 Deployment 选项出现: war 模式 可以称之为发布模式.先将 WEB 工程打成 war 包,然后再将其上传到服务器进行发布. war expl ...
- random方法
random.randint(1,10) # 产生 1 到 10 的一个整数型随机数 ,包括1和10random.random() # 产生 0 到 1 之间的随机浮点数rand ...
- RecyclerView实现拖动排序和滑动删除功能
RecyclerView 的拖动排序需要借助一下 ItemTouchHelper 这个类,ItemTouchHelper 类是 Google 提供的一个支持 RecyclerView 滑动和拖动的一个 ...
- ANTLR随笔(二)
安装ANTLR 作者的电脑是MAC的操作系统macOS Catalina 10.15.2. 安装步骤后linux操作的系统的一样, Windows系统大致步骤一样,但是环境变量等配置有差别,作者很久没 ...
- A. Remainder Codeforces Round #560 (Div. 3)
A. Remainder Codeforces Round #560 (Div. 3) You are given a huge decimal number consisting of nn dig ...
- Java并发基础03. 传统线程互斥技术—synchronized
在多个线程同时操作相同资源的时候,就会遇到并发的问题,如银行转账啊.售票系统啊等.为了避免这些问题的出现,我们可以使用synchronized关键字来解决,下面针对synchronized常见的用法做 ...
- Pytest系列(7) - skip、skipif跳过用例
如果你还想从头学起Pytest,可以看看这个系列的文章哦! https://www.cnblogs.com/poloyy/category/1690628.html 前言 pytest.mark.sk ...
- vs code 关闭保存自动格式化 formatonsave - [vscode] - [html]
有时候Ctrl+s保存,html代码哥格式会紊乱. 造成这个原因一般是我们基本都在用的一个插件: ![](https://img2018.cnblogs.com/blog/1735896/201912 ...
- ERROR:TypeError: Cannot read property 'upgrade' of undefined
- 下载安装配置 Scala-2.12.11
文章更新于:2020-03-24 安装惯例,文件附上链接放在文首. 文件名:scala-2.12.11.tgz 文件大小:19.83 MB 下载链接:https://downloads.lightbe ...