一、准备阶段🍉
创建好web工程后(不会创建的可以看我前几篇文章)
看不懂的小伙伴可以看一下我的第一篇文章里面有详细的介绍
1.引入依赖🥝
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.example</groupId>
<artifactId>shiro</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<packaging>war</packaging>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>8</source>
<target>8</target>
</configuration>
</plugin>
</plugins>
</build>
<artifactId>shrio-05</artifactId>
<name>Archetype - shrio-05</name>
<url>http://maven.apache.org</url>
<dependencies>
<!--shiro和redis整合的依赖-->
<dependency>
<groupId>org.crazycake</groupId>
<artifactId>shiro-redis</artifactId>
<version>2.4.6</version>
</dependency>
<!--shiro-spring整合的依赖-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.7.0</version>
</dependency>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.31</version>
</dependency>
<!--spring的相关依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.15.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.15.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.2.15.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.2.15.RELEASE</version>
</dependency>
<!--mybatis的依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.9</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.7</version>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.28</version>
</dependency>
<!--jackson-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.15.2</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.83_noneautotype</version>
</dependency>
<!--jsp servlet-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<!--druid依赖-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.8</version>
</dependency>
</dependencies>
</project>
2.编写spring.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" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://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 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--包扫描-->
<context:component-scan base-package="com.lzq"/>
<!--2.注解驱动-->
<mvc:annotation-driven/>
<!--3.静态资源放行-->
<mvc:default-servlet-handler/>
<!--4.视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!--数据源-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="username" value="root"/>
<property name="password" value="123456"/>
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/db2?serverTimezone=Asia/Shanghai"/>
</bean>
<!--SqlSessionFactory 加载mybatis的配置-->
<bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!--映射文件所在的路径-->
<property name="mapperLocations" value="classpath:mapper/*.xml"/>
</bean>
<!--7.设置dao接口的代理实现类-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="sessionFactory"/>
<!--dao接口所在的包-->
<property name="basePackage" value="com.lzq.dao"/>
</bean>
<!--事务管理-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--开启事务的注解驱动-->
<tx:annotation-driven/>
<!--shiro和spring整合的配置-->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="myRealm"/>
<!--设置缓存管理器-->
<property name="cacheManager" ref="redisCacheManager"/>
</bean>
<!--redis缓存管理器-->
<bean id="redisCacheManager" class="org.crazycake.shiro.RedisCacheManager">
<!--缓存管理器的地址redisManager-->
<property name="redisManager" ref="redisManager"/>
</bean>
<!--redis管理器-->
<bean id="redisManager" class="org.crazycake.shiro.RedisManager">
<property name="host" value="192.168.179.129"/>
<property name="database" value="1"/>
<property name="port" value="6379"/>
</bean>
<bean id="myRealm" class="com.lzq.realm.MyRealm">
<property name="credentialsMatcher" ref="credentialsMatcher"/>
</bean>
<!--加密器-->
<bean id="credentialsMatcher" class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
<property name="hashAlgorithmName" value="MD5"/>
<property name="hashIterations" value="1024"/>
</bean>
<!--shiro过滤器 id:必须和web.xml里面的过滤器配置的名称对应-->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager"/>
<!--未登录时跳转的路径-->
<property name="loginUrl" value="/unlogin"/>
<!--过滤规则-->
<property name="filterChainDefinitions">
<value>
/login=anon
/** =authc
</value>
</property>
<!--引入自定义过滤器-->
<property name="filters">
<map>
<entry key="authc" value-ref="myFilter"/>
</map>
</property>
</bean>
<!--将自定义的过滤器类对象交给ioc容器-->
<bean id="myFilter" class="com.lzq.filter.LoginFilter">
</bean>
</beans>
3.编写web.xml配置文件🥝
<?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">
<!--配置前端控制器-->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring.xml</param-value>
</init-param>
<!--tomcat启动时加载该类-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--shiro的过滤器:必须和ShiroFilterFactoryBean的id一致-->
<filter>
<filter-name>shiroFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>shiroFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
4.需要用到的实体类🥝
pojo层
package com.lzq.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Permission {
private String perid;
private String pername;
private String percode;
}
vo层
package com.lzq.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private Integer userid;
private String username;
private String userpwd;
private String sex;
private String address;
private String salt;
}
二、编码阶段🍉
1.dao层🥝
package com.lzq.dao;
import com.lzq.pojo.Permission;
import com.lzq.pojo.User;
import java.util.List;
public interface UserDao2 {
User aaa(String username);
List<Permission> selectpermissionByUserid(Integer userid);
}
2.service层🥝
package com.lzq.service;
import com.lzq.pojo.User;
import java.util.List;
public interface UserService {
User findAllByusername(String username);
List<String> selectPermissionByuserid(Integer userid);
}
impl
package com.lzq.service.impl;
import com.lzq.dao.UserDao2;
import com.lzq.pojo.Permission;
import com.lzq.pojo.User;
import com.lzq.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.stream.Collectors;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao2 userDao;
public User findAllByusername(String username) {
User user = userDao.aaa(username);
return user;
}
public List<String> selectPermissionByuserid(Integer userid) {
List<Permission> permissions = userDao.selectpermissionByUserid(userid);
List<String> collect = permissions.stream().map(item -> item.getPercode()).collect(Collectors.toList());
return collect;
}
}
3.controller层🥝
登录页面的congtroller层
package com.lzq.controller;
import com.lzq.vo.LoginVo;
import com.lzq.vo.Result;
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.ResponseBody;
@Controller
public class UserController2 {
@GetMapping("/unlogin")
@ResponseBody
public Result unlogin(){
return new Result(401,"请先登录",null);
}
@PostMapping ("/login")
@ResponseBody
public Result login(LoginVo loginVo){
Subject subject = SecurityUtils.getSubject();
System.out.println(loginVo.getUsername());
UsernamePasswordToken token = new UsernamePasswordToken(loginVo.getUsername(),loginVo.getPassword());
try {
subject.login(token);
return new Result(200,"登录成功",null);
}catch (Exception e){
System.out.println("登录失败");
return new Result(500,"账号或密码错误",null);
}
}
}
首页授权功能的controller层
package com.lzq.controller;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/user")
public class UserController {
@GetMapping("/query")
// @RequiresPermissions(value = {"user:query","user:delete"},logical = Logical.OR)
@RequiresPermissions(value = "user:query")
public String query(){
return "user:query------------------------";
}
@GetMapping("/update")
@RequiresPermissions(value = "user:update")
public String update(){
return "user:update------------------------";
}
@GetMapping("/delete")
@RequiresPermissions(value = "user:delete")
public String delete(){
return "user:delete------------------------";
}
@GetMapping("/insert")
@RequiresPermissions(value = "user:insert")
public String insert(){
return "user:insert------------------------";
}
@GetMapping("/export")
@RequiresPermissions(value = "user:export") //该注解不能别识别
public String export(){
return "user:export------------------------";
}
}
4.realm层🥝
该层代码为shiro安全框架代码完成了登录认证和授权功能
package com.lzq.realm;
import com.fasterxml.jackson.databind.deser.std.NumberDeserializers;
import com.lzq.pojo.User;
import com.lzq.service.UserService;
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.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
public class MyRealm extends AuthorizingRealm {
@Autowired
private UserService userService;
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
//获取当前登录者的账号
User user = (User) principals.getPrimaryPrincipal();
//从数据库查询数据
List<String> permissions = userService.selectPermissionByuserid(user.getUserid());
if (permissions.size()!=0){
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
info.addStringPermissions(permissions);
return info;
}
return null;
}
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
//从shiro框架权限管理器中获取用户名
String username = token.getPrincipal().toString();
//根据传入的用户名到数据库查找是否存在该用户信息
User user = userService.findAllByusername(username);
if (user != null) {
//获取到盐 因为数据库中存储的密码都是加密过的解码需要盐
ByteSource source = ByteSource.Util.bytes(user.getSalt());
//将账户、密码、盐、给realm起的别名 交给 shiro框架处理比对
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getUserpwd(), source, this.getName());
return info;
}
return null;
}
}
5.filter层🥝
该为文件层
LoginFilter该类代码是为了过滤未登录操作使其重新返回到登录页面
package com.lzq.filter;
import com.alibaba.fastjson.JSON;
import com.lzq.vo.Result;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.PrintWriter;
public class LoginFilter extends FormAuthenticationFilter {
//当未登录账号访问接口时,会触发该方法。
//默认内容是重定向到登录页面---重写改为返回json数据
@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
//解决响应数据的中文乱码问题
response.setContentType("application/json;charset=utf-8");
//通过io流的方式将响应返还给前端
PrintWriter writer = response.getWriter();
Result result = new Result(401, "请先登录", null);
//把java对象转换为json字符串 ----JSON java封装的工具类
String jsonstring = JSON.toJSONString(result);
writer.print(jsonstring);
//刷新io流
writer.flush();
//关闭io流资源
writer.close();
return false;
}
}
6.hendler层🥝
该层是拦截异常业务代码
MyHendlr
package com.lzq.hendler;
import com.lzq.vo.Result;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
@ControllerAdvice
public class MyHendlr {
@ExceptionHandler(value = UnauthorizedException.class)
@ResponseBody
public Result UnauthorizedException(UnauthorizedException e){
e.printStackTrace();
return new Result(403,"权限不足",null);
}
}
7.mapper层🥝
<?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.lzq.dao.UserDao2">
<select id="aaa" resultType="com.lzq.pojo.User">
select * from user where username=#{username}
</select>
<select id="selectpermissionByUserid" resultType="com.lzq.pojo.Permission">
select p.* from user_role ur join role_permission rp on ur.roleId=rp.roleid
join permission p on rp.perid=p.perid where ur.userid=#{userId}
</select>
</mapper>
8.前端页面🥝
只是测试功能,前端页面写的很简单
登录页面
<%--
Created by IntelliJ IDEA.
User: LIYANGCUNZHUANG
Date: 2023/7/6
Time: 16:09
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登录页面</title>
</head>
<body>
<form method="post" action="/login">
账号:<input type="text" name="username"><br><br>
密码:<input type="text" name="password"><br><br>
<input type="submit" value="登录">
</form>
</body>
</html>
登陆成功页面
<%--
Created by IntelliJ IDEA.
User: LIYANGCUNZHUANG
Date: 2023/7/6
Time: 13:49
To change this template use File | Settings | File Templates.
--%>
<%@ 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:hasPermission name="user:query"><a href="/user/query">查询用户</a></shiro:hasPermission>
<shiro:hasPermission name="user:update"><a href="/user/update">修改用户</a></shiro:hasPermission>
<shiro:hasPermission name="user:delete"><a href="/user/delete">删除用户</a></shiro:hasPermission>
<shiro:hasPermission name="user:insert"><a href="/user/insert">添加用户</a></shiro:hasPermission>
<shiro:hasPermission name="user:export"><a href="/user/export">导出用户</a></shiro:hasPermission>
</body>
</html>