共计 11444 个字符,预计需要花费 29 分钟才能阅读完成。
1. 创立一个 springboot 我的项目
选中 web 和 thymeleaf
1.1 新建 index.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1> 首页 </h1>
<p th:text="${msg}"></p>
</body>
</html>
1.2 创立一个 controller
package com.yao.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class MyController {@RequestMapping({"/","/index"})
public String toIndex(Model model){model.addAttribute("msg","hello,Shiro");
return "index";
}
}
肯定要记住 shiro 的三大对象
1.subject:用户
2.SecurityManager:治理所有用户
3.Realm:连贯数据
1.3 导入整合用的依赖包
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.4.1</version>
</dependency>
1.4 创立一个 config(ShiroConfig),并编写他
package com.yao.config;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ShiroConfig {
//ShiroFilterFactoryBean
//DefaultWebSecurityManager
// 创立 realm 对象,这个 realm 对象须要自定义
}
1.5 创立本人的一个 realmconfig,也就是在 config 中创立另外一个配置类 UserRealm
package com.yao.config;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
// 自定义的 UserRealm
public class UserRealm extends AuthorizingRealm {
// 受权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {System.out.println("受权。。。");
return null;
}
// 认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {System.out.println("认证。。。");
return null;
}
}
1.6 将 UserRealm 注册到 ShiroConfig 外面去,是咱们本人写的这个类被 spring 托管
1.7 新建两个测试页面并从新写一下 index 页面
add.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>add</h1>
</body>
</html>
update.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>update</h1>
</body>
</html>
index.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1> 首页 </h1>
<p th:text="${msg}"></p>
<hr>
<a th:href="@{/user/add}">add</a> | <a th:href="@{/user/update}">update</a>
</body>
</html>
1.8 编写 controller 层
package com.yao.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class MyController {@RequestMapping({"/","/index"})
public String toIndex(Model model){model.addAttribute("msg","hello,Shiro");
return "index";
}
@RequestMapping("/user/add")
public String add(){return "user/add";}
@RequestMapping("/user/update")
public String update(){return "user/update";}
}
1.9 增加过滤器
还是在 shiroconfig 中退出:
// 增加 Shiro 的内置过滤器
/*
anon:无需认证就能够拜访
authc:必须认证了能力通过
user:必须领有记住我性能能力用
perms:领有对某个资源的权限才能够拜访
role:领有某个角色权限能力拜访
*/
Map<String,String> filterMap = new LinkedHashMap<>();
// filterMap.put("/user/add","authc");
// filterMap.put("/user/update","authc");
filterMap.put("/user/*","authc");
bean.setFilterChainDefinitionMap(filterMap);
// 设置登录的申请
bean.setLoginUrl("/toLogin");
return bean;
这里心愿没有认证就从 add 和 update 跳到 login 页面因而还要写一个 login 页面和改写 controller
controller 层:
@RequestMapping("/toLogin")
public String toLogin(){return "login";}
login 页面:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> 登录 </title>
</head>
<body>
<form>
<p> 用户名:<input type="text" name="username"></p>
<p> 明码:<input type="text" name="password"></p>
<p><input type="submit"></p>
</form>
</body>
</html>
1.10 下面曾经实现了页面拦挡的性能接下来实现用户认证的工作
login.html:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title> 登录 </title>
</head>
<body>
<p th:text="${msg}" ></p>
<form th:action="@{/login}">
<p> 用户名:<input type="text" name="username"></p>
<p> 明码:<input type="text" name="password"></p>
<p><input type="submit"></p>
</form>
</body>
</html>
controller:
@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);// 执行登陆的办法,如果没有异样就 ok 了
return "index";
} catch (UnknownAccountException e) {model.addAttribute("msg","用户名谬误");
return "login";
} catch (IncorrectCredentialsException e){model.addAttribute("msg","明码谬误");
return "login";
}
}
UserRealm:
// 认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {System.out.println("认证。。。");
// 用户名,明码 数据库中取
String name = "root";
String password = "123456";
UsernamePasswordToken userToken = (UsernamePasswordToken) token;
if(!userToken.getUsername().equals(name)){return null;// 它这里会主动抛出后面的用户名谬误的异样}
// 明码认证不让你做,它本人做,他不让你接触明码
return new SimpleAuthenticationInfo("",password,"");
}
}
间接测试即可发现以上性能根本实现。
package com.yao.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class MyController {@RequestMapping({"/","/index"})
public String toIndex(Model model){model.addAttribute("msg","hello,Shiro");
return "index";
}
}
2.springboot 整合 mybatis
2.1 导入依赖
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.12</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.0</version>
</dependency>
2.2 编写配置文件 application.yml
spring:
datasource:
username: root
password: 892095368llq
#?serverTimezone=UTC 解决时区的报错
url: jdbc:mysql://localhost:3306/yao?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
#Spring Boot 默认是不注入这些属性值的,须要本人绑定
#druid 数据源专有配置
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
#配置监控统计拦挡的 filters,stat: 监控统计、log4j:日志记录、wall:进攻 sql 注入
#如果容许时报错 java.lang.ClassNotFoundException: org.apache.log4j.Priority
#则导入 log4j 依赖即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4j
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
2.3 编写配置文件 application.properties 并新建 mapper 文件夹
application.properties
mybatis.type-aliases-package=com.yao.pojo
mybatis.mapper-locations=classpath:mapper/*.xml
2.4 创立 pojo 层,并配置 lombok
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.10</version>
</dependency>
编写一个 User.java
package com.yao.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;
private String name;
private String pwd;
}
2.4 创立 mapper 层,并写出绝对应的 mapper 接口和 resources 中的对应的 mapper 实现
UserMapper 接口
package com.yao.mapper;
import com.yao.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
@Repository
@Mapper
public interface UserMapper {public User queryUserByName(String name);
}
mapper。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.yao.mapper.UserMapper">
<select id="queryUserByName" parameterType="String" resultType="User">
select * from user where name = #{name}
</select>
</mapper>
UserService.interface
package com.yao.service;
import com.yao.pojo.User;
public interface UserService {public User queryUserByName(String name);
}
UserServiceImpl.java
package com.yao.service;
import com.yao.mapper.UserMapper;
import com.yao.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements UserService{
@Autowired
UserMapper userMapper;
@Override
public User queryUserByName(String name) {return userMapper.queryUserByName(name);
}
}
2.6 在 test 中测试
package com.yao;
import com.yao.service.UserService;
import com.yao.service.UserServiceImpl;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class ShiroSpringbootApplicationTests {
@Autowired
UserServiceImpl userService;
@Test
void contextLoads() {System.out.println(userService.queryUserByName("幺幺"));
}
}
测试胜利,持续写
2.7 更改 UserRealm
package com.yao.config;
import com.yao.pojo.User;
import com.yao.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
// 自定义的 UserRealm
public class UserRealm extends AuthorizingRealm {
@Autowired
UserService userService;
// 受权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {System.out.println("受权。。。");
return null;
}
// 认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {System.out.println("认证。。。");
UsernamePasswordToken userToken = (UsernamePasswordToken) token;
// 连贯实在数据库
User user = userService.queryUserByName(userToken.getUsername());
if (user==null){return null;}
// 明码认证不让你做,它本人做,他不让你接触明码
return new SimpleAuthenticationInfo("",user.getPwd(),"");
}
}
2.8 增加明码加密
// 还有一个 md5 加密,集成了 hashcode 是不可逆的
// 比方你的明码是 123456
// md5(123456,32) = e10adc3949ba59abbe56e057f20f883e
// md5(123456,16) = 49ba59abbe56e057
//MD5 盐值加密 e10adc3949ba59abbe56e057f20f883eusername
// 明码认证不让你做,它本人做,他不让你接触明码
return new SimpleAuthenticationInfo("",user.getPwd(),"");
2.9 申请受权实现
==============
2.10 绑定 thymeleaf
package com.yao.mapper;
import com.yao.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
@Repository
@Mapper
public interface UserMapper {public User queryUserByName(String name);
}
举荐浏览
为什么阿里巴巴的程序员成长速度这么快?
纳尼?SpringCloud 要被淘汰了?
《飞马打算》到底是什么?能够让数万程序员为之着迷
一年半开发教训拿多少钱适合?
看完三件事
如果你感觉这篇内容对你还蛮有帮忙,我想邀请你帮我三个小忙:
点赞,转发,有你们的『点赞和评论』,才是我发明的能源。
关注公众号『Java 斗帝』,不定期分享原创常识。
同时能够期待后续文章 ing????
正文完