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(二)的更多相关文章

  1. Shiro笔记(二)身份验证

    Shiro笔记(二)身份验证 一.核心代码 @Test public void helloWorldTest(){ IniSecurityManagerFactory factory = new In ...

  2. Shiro 自定义登陆、授权、拦截器

    Shiro 登陆.授权.拦截 按钮权限控制 一.目标 Maven+Spring+shiro 自定义登陆.授权 自定义拦截器 加载数据库资源构建拦截链 使用总结: 1.需要设计的数据库:用户.角色.权限 ...

  3. 解决shiro自定义filter后,ajax登录无法登录,并且无法显示静态资源的问题

    这个问题困扰了我一天,看了下面两个文章,豁然开朗: https://www.cnblogs.com/gj1990/p/8057348.html https://412887952-qq-com.ite ...

  4. Android自定义视图二:如何绘制内容

    这个系列是老外写的,干货!翻译出来一起学习.如有不妥,不吝赐教! Android自定义视图一:扩展现有的视图,添加新的XML属性 Android自定义视图二:如何绘制内容 Android自定义视图三: ...

  5. PHP自定义生成二维码跳转地址

      比较简单的一款PHP自定义生成二维码跳转地址,手机端微信扫码,自动跳转到定义好的链接.支持自定义生成二维码尺寸.间距等.    鼠标悬浮显示二维码弹出层,离开后消失.js实现,代码如下: $(fu ...

  6. vue2.0 自定义 生成二维码(QRCode)组件

    1.自定义 生成二维码组件 QRCode.vue <!-- 生成二维码 组件 --> <template> <canvas class="qrcode-canv ...

  7. Apcahe Shiro学习笔记(二):通过JDBC进行权限控制

    一.概述: 官方对Realm(领域)的描述:https://www.infoq.com/articles/apache-shiro 其功能本质上是一个安全特定的DAO,用于链接数据持久层(任何形式的都 ...

  8. shiro基础学习(二)—shiro认证

    一.shiro简介      shiro是apache旗下一个开源框架,它将软件系统的安全认证相关的功能抽取出来,实现用户身份认证.权限授权.加密.会话管理等功能,组成了一个通用的安全认证框架. 以下 ...

  9. Shiro自定义realm实现密码验证及登录、密码加密注册、修改密码的验证

    一:先从登录开始,直接看代码 @RequestMapping(value="dologin",method = {RequestMethod.GET, RequestMethod. ...

随机推荐

  1. OpenCV-Python教程简介 | 一

    OpenCV OpenCV由Gary Bradsky于1999年在英特尔创立,第一版于2000年问世.Vadim Pisarevsky加入Gary Bradsky,一起管理英特尔的俄罗斯软件OpenC ...

  2. Kaggle大牛小姐姐自述:我是怎么成为竞赛中Top 0.3%的 | 干货攻略

    天天跟数据打交道的研究人员,都有一个成为Kaggle顶级大师(Grandmaster)的梦想. 但每年的Kaggle参赛团队众多,通常一个项目都有数千人至上万人报名,如何在其中脱颖而出? 最近,自动化 ...

  3. 面试刷题28:如何写出安全的java代码?

    对jdk,jvm,java应用程序的攻击多种多样?那么从java程序员的角度,如何写出安全的代码呢? 我是李福春,我在准备面试,今天的题目是:如何写出安全的java代码? 答:这个需要从功能设计到实现 ...

  4. Nginx是什么东东?

    Nginx的产生 没有听过Nginx?那么一定听过它的"同行"Apache吧!Nginx同Apache一样都是一种WEB服务器.基于REST架构风格,以统一资源描述符(Unifor ...

  5. Java 数组 字符 函数

    一. 1. package Hello; import java.util.Scanner; public class hello_test { public static void main(Str ...

  6. C 送外卖

    时间限制 : - MS   空间限制 : 365536 KB  评测说明 : 时限1000ms 问题描述 暑期期间,何老板闲来无事,于是买了辆摩托车,签约某团外卖,跑起来送外卖的业务.  何老板负责的 ...

  7. ScrollViewer - 可用鼠标拖动滚动的列表框

    ScrollViewer添加附加属性: using System; using System.Collections.Generic; using System.Windows; using Syst ...

  8. Java多线程并发工具类-信号量Semaphore对象讲解

    Java多线程并发工具类-Semaphore对象讲解 通过前面的学习,我们已经知道了Java多线程并发场景中使用比较多的两个工具类:做加法的CycliBarrier对象以及做减法的CountDownL ...

  9. Shell:Day03笔记

    编程原理:1.编程结束  驱动 硬件默认是不能使用的   CPU控制硬件   不同的厂家硬件设备之间需要进行指令沟通,就需要驱动程序来进行“翻译”    编程语言的分类:  高级语言.超高级语言需要翻 ...

  10. php--理解PHP的依赖注入和laravel的服务容器

    写在前面 为了了解laravel的服务容器在网上搜了许多文章,其中大多数都有其侧重点,没有很系统的一套东西以供参考,看完之后仍觉似乎少了一根把他们串起来的绳子,近期有幸拜读了陈昊的<Larave ...