日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

springboot整合shiro+mybatis-plus

發布時間:2024/9/19 编程问答 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 springboot整合shiro+mybatis-plus 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

文章目錄

        • Shiro框架簡介
        • 環境搭建springboot+shiro+mybatis-plus+thymeleaf
          • 1.創建Spring Boot項目,集成Shiro及相關組件
          • 2.準備一個sql表
          • 3.配置yml
          • 4.創建表的實體類
          • 5.創建mybatis-plus的basemapper接口
          • 6.創建UserService接口實現
          • 7.創建UserServiceImpl業務邏輯
          • 8.編寫自定義Realm認證授權
          • 9.編寫Shiro的配置類
          • 10.編寫controller控制器
          • 11.編寫controller對應的界面html
          • 12.啟動器測試
        • shiro完美解釋

Shiro框架簡介

Apache Shiro是一個強大且易用的Java安全框架,執行身份認證丶授權丶密碼和會話管理。
以用戶登錄為例-多圖參考↓


Shiro主要用來用戶認證和用戶授權

用戶認證 — 用戶身份識別。得知道來的人是誰;
用戶授權 — 用戶權限訪問控制。得知道來的人有沒有資格進來,又不是“我家大門常打開”;

環境搭建springboot+shiro+mybatis-plus+thymeleaf

springboot+shiro+mybatis-plus+thymeleaf
目錄結構

1.創建Spring Boot項目,集成Shiro及相關組件


pom.xml

<!--mybatis-plus--><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.4.2</version></dependency> <!--mysql--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency> <!--shiro--><dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-spring</artifactId><version>1.7.1</version></dependency>
2.準備一個sql表
創建數據庫 create database 數據庫名;選擇數據庫 use 數據庫名;

創建數據表

create database shirompdb;use shirompdb;create table account(id int AUTO_INCREMENT,name varchar(30) default null,password varchar(30) default null,perms varchar(30) default null,primary key(id) )engine=innodb charset=utf8;

mysql連接idea并且添加幾個用戶

3.配置yml
spring:datasource:url: jdbc:mysql://localhost:3306/shirompdbusername: rootpassword: guohuidriver-class-name: com.mysql.cj.jdbc.Driverthymeleaf:prefix: classpath:/templates
4.創建表的實體類

pojo

@Data @AllArgsConstructor @NoArgsConstructor @TableName("account")//account 對應數據庫的表 public class user {private Integer id;private String name;private String password;private String perms; }
5.創建mybatis-plus的basemapper接口

mapper

@Repository public interface UserMapper extends BaseMapper<user> {}
6.創建UserService接口實現

service

@Service public interface UserService {public user queryUserByName(String name); }
7.創建UserServiceImpl業務邏輯

service/impl

@Service public class UserServiceImpl implements UserService {@Autowiredprivate UserMapper userMapper;@Overridepublic user queryUserByName(String name) {QueryWrapper wrapper = new QueryWrapper();wrapper.eq("name",name);return userMapper.selectOne(wrapper);} }
8.編寫自定義Realm認證授權

shiro

public class AccountRealm extends AuthorizingRealm {@Autowiredprivate UserService userService;//。1 自定義的Realm@Override//授權protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {System.out.println("執行了授權===》doGetAuthorizationInfo");SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();//拿到當前登陸的對象Subject subject = SecurityUtils.getSubject();//拿到account對象user currentUser = (user) subject.getPrincipal();//設置當前用戶權限info.addStringPermission(currentUser.getPerms());return info;}@Override//認證protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {System.out.println("執行了認證===》doGetAuthenticationInfo");//連接數據庫UsernamePasswordToken Token = (UsernamePasswordToken) authenticationToken;user user = userService.queryUserByName(Token.getUsername());if (user != null) {return new SimpleAuthenticationInfo(user, user.getPassword(), getName());}return null;} }
9.編寫Shiro的配置類

config

@Configuration public class ShiroConfig {//3. 連接前端 ShiroFilterFactoryBean@Beanpublic ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("defaultWebSecurityManager") DefaultWebSecurityManager defaultWebSecurityManager) {ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();//設置安全管理器bean.setSecurityManager(defaultWebSecurityManager);/* 添加Shiro的內置過濾器anon: 無需認證就可以訪問authc: 必須認證了才能訪問user: 必須擁有我 記住我 功能才能訪問perms: 擁有對莫個資源的權限才能訪問role: 擁有莫個角色權限才能訪問*/LinkedHashMap<String, String> filterMap = new LinkedHashMap<>();filterMap.put("/user/add", "perms[user:add]");//user,的add anon設置所有人可以訪問filterMap.put("/user/update", "perms[user:update]");//user,的update authc設置認證了才能訪問bean.setFilterChainDefinitionMap(filterMap);bean.setLoginUrl("/tologin");bean.setUnauthorizedUrl("/noauth");return bean;}//2. 接管對象 DafaultWebSecurityManager@Beanpublic DefaultWebSecurityManager defaultWebSecurityManager(@Qualifier("userRealm") AccountRealm userRealm) {DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();//關聯userReal 接管reaml對象securityManager.setRealm(userRealm);return securityManager;}//1. 創建realm對象 、需要自定義@Beanpublic AccountRealm userRealm() {return new AccountRealm();} }
10.編寫controller控制器

controller

@Controller public class MyController {@RequestMapping("/index")public String toIndex(Model model) {model.addAttribute("msgTest", "hello,shiro");return "index";}@RequestMapping("user/add")public String add() {return "user/add";}@RequestMapping("user/update")public String update() {return "user/update";}@RequestMapping("/tologin")public String toLonin() {return "login";}@RequestMapping("/login")public String login(String username, String password, Model model) {//獲取當前的用戶Subject subject = SecurityUtils.getSubject();//封裝用戶的登錄數據UsernamePasswordToken token = new UsernamePasswordToken(username, password);try {//執行登錄的方法subject.login(token);return "index";} catch (UnknownAccountException e) {//用戶名不存在model.addAttribute("msg","用戶名錯誤");return "login";}catch (IncorrectCredentialsException e){//密碼錯誤model.addAttribute("msg","密碼錯誤");return "login";}}@RequestMapping("/noauth")@ResponseBodypublic String unauthorized(){return "未授權無法訪問此頁面";} }
11.編寫controller對應的界面html

templates\index.html

<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"xmlns:shiro="http://www.thymeleaf.org/thymeleaf-extras-shiro"> <head><meta charset="UTF-8"><title>shiro學習</title> </head> <body> <H1>首頁</H1> <p th:test="${msgTest}"></p> <hr> <div shiro:hasPermission="user:add"></div> <a th:href="@{/user/add}">add</a> <div shiro:hasPermission="user:update"></div> <a th:href="@{/user/update}">update</a> </body> </html>

templates\login.html

<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head><meta charset="UTF-8"><title>shiro登錄</title> </head> <body> <div><p th:text="${msg}" style="color: #ff0000"></p><form method="get" th:action="@{/login}"><p>用戶名:<input type="text" name="username"></p><p>密 碼:<input type="text" name="password"></p><p><input type="submit" value="登錄"></p></form> </div> </body> </html>

templates\user\add.html

<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>加一個用戶</title> </head> <body> <h1>add</h1> </body> </html>

templates\user\update.html

<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>修改一個用戶</title> </head> <body> <h1>update</h1> </body> </html>
12.啟動器測試

啟動類上添加@MapperScan(“com.guohui.mapper”) 掃描你自己mapper

@SpringBootApplication @MapperScan("com.guohui.mapper") public class SpringbootShirotestApplication {public static void main(String[] args) {SpringApplication.run(SpringbootShirotestApplication.class, args);} }

啟動測試
用戶認證 — 用戶身份識別

用戶授權 — 用戶權限訪問控制。

shiro完美解釋

讓 Apache Shiro 保護你的應用

總結

以上是生活随笔為你收集整理的springboot整合shiro+mybatis-plus的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。