需要解决的问题:
web对应的自动配置类:WebMvcAutoConfiguration
方式一:使用webjars的方式
去官网引入webjars的maven依赖
<dependency>
<groupId>org.webjarsgroupId>
<artifactId>jqueryartifactId>
<version>3.4.1version>
dependency>
成功引入之后,启动服务后。访问路径为:localhost:8080/webjars/(我们的资源文件)
方式二:在resource目录下新建文件
ResourceProperties类的部分源码
即静态资源可以存放的位置为:
外部访问的优先级:resources > static(默认) > public
源码如图:
新建一个首页,文件命名为index.html,可以根据适当的需求,自行放在public、static、templates等目录的其中一个下。
访问路径为:localhost:8080
对比JSP技术,它是将后端传过来的数据,绑定到对应的形式上,继而达到前端显示后端的数据。Thymeleaf也是将后端传回来的数据与前端的视图进行绑定,达到了与JSP类似的效果(JSP也是一种模板引擎)。Spring Boot推荐使用Thymeleaf模板引擎。
官方网址:https://www.thymeleaf.org
使用Thymeleaf需要导入对应的依赖
html页面可以引入相应相应的xmlns(xml name space):xmlns:th=“http://www.thymeleaf.org”,防止看到报异常看着不舒服
Sping Boot文档中的启动器:
对应的pom文件
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>
测试案例:
index的控制器类
package pers.mobian.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class Index {
@RequestMapping("/index")
public String index(Model model) {
model.addAttribute("msg", "hello SpringBoot");
return "index";
}
}
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Titletitle>
head>
<body>
<h1>首页h1>
${msg}
<div th:text="${msg}">div>
body>
html>
执行结果
总结:当我们访问首页的对应映射后,他会对数据进行封装,然后通过Thymeleaf模板引擎渲染到前端界面。并且前端的接收方式也要变成
Thymeleaf基本语法之:th:each
、th:utext
、th:text
@Controller
public class Index {
@RequestMapping("/index")
public String index(Model model) {
model.addAttribute("msg","首页"
);
model.addAttribute("users", Arrays.asList("mobian1","mobian2","mobian3"));
return "index";
}
}
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Titletitle>
head>
<body>
<div th:utext="${msg}">div>
<div th:text="${msg}">div>
<div th:each="user:${users}" th:text="${user}">div>
body>
html>
测试结果:
测试代码:
package pers.mobian.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.Locale;
//如果想要自定义一些功能,只需要重写这个组件,然后将它交给springboot,springboot就会帮我们自动装配
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
//ViewResolver 实现了视图解析器接口的类,我们就可以把它看做视图解析器
@Bean
public ViewResolver myViewResolver(){
return new MyViewResolver();
}
//自定义了一个自己的视图解析器MyViewResolver
public static class MyViewResolver implements ViewResolver{
@Override
public View resolveViewName(String viewName, Locale locale) throws Exception {
return null;
}
}
}
补充
package pers.mobian.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.Locale;
//如果我们呢要扩展springmvc,官方建议我们这样去做
@Configuration
@EnableWebMvc //这个注解就是导入一个:DelegatingWebMvcConfiguration:从容器中获取所有的webmvcconfig(如果我们自定义了config类就不能添加这个注解)
public class MyMvcConfig implements WebMvcConfigurer {
//视图跳转
@Override
public void addViewControllers(ViewControllerRegistry registry) {
//访问的url为/mobian,跳转的视图是test.jsp
registry.addViewController("/mobian").setViewName("test");
}
}
总结:在springboot中,有非常多的xxxConfiguration帮助我们进行扩展,只要看见这种类,那么它就会改变或者扩展了我们原来spring的功能
1、搞定前端: 明确页面的样子,方便数据的出现
2、设计数据库(数据库设计是难点)
3、前端能够使其能够自动运行,独立化工程
4、数据接口如何对接:json,对象all in one
5、前后端联调测试
前期准备工作:
花费一个月的时间去研究
在进行该步操作时,创建的SpringBoot项目需要的依赖为:JDBC API 、MySQL Driver
导入成功后对应的依赖是
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-jdbcartifactId>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<scope>runtimescope>
dependency>
由于又是一个web项目,所以还需要添加web的启动器
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
整合案例步骤:
使用IDEA连接已存在的数据库表
新建application.yaml文件,配置数据库
spring:
datasource:
username: root
password:
#注意要配置时区
url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
#springboot默认配置的数据库连接使mysql 8.x(虽然我的数据库是5.5,但还是建议使用8.x的)
#com.mysql.cj.jdbc.Driver mysql 8.x
#com.mysql.jdbc.Driver mysql 5.x
driver-class-name: com.mysql.cj.jdbc.Driver
新建一个控制器类JDBCController,处理JDBC的CRUD
package pers.mobian.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
@RestController
public class JDBCController {
/**
* Spring Boot 默认提供数据源为org.springframework.jdbc.core.JdbcTemplate
* JdbcTemplate 中会自己注入数据源,用于简化 JDBC操作
* 还能避免一些常见的错误,使用起来也不用再自己来关闭数据库连接
*/
@Autowired
JdbcTemplate jdbcTemplate;
//查找学生
@RequestMapping("/selectUser")
public List<Map<String, Object>> selectUser() {
String sql = "select * from user";
List<Map<String, Object>> mapList = jdbcTemplate.queryForList(sql);
return mapList;
}
//新增学生
@RequestMapping("/addUser")
public String addUser() {
String sql = "insert into mybatis.user(id,name,pwd) values (1,'小明','2222')";
jdbcTemplate.update(sql);
return "addUser ok";
}
//删除学生
@RequestMapping("/deleteUser/{id}")
public String deleteUser(@PathVariable("id") int id) {
String sql = "delete from mybatis.user where id = ? ";
jdbcTemplate.update(sql, id);
return "deleteUser ok";
}
//修改学生
@RequestMapping("/updateUser/{id}")
public String updateUser(@PathVariable("id") int id) {
String sql = "update mybatis.user set name=?,pwd=? where id=" + id;
Object[] objects = new Object[2];
objects[0] = "mobian";
objects[1] = "88888";
jdbcTemplate.update(sql, objects);
return "updateUser ok";
}
}
补充:
在测试类中打印数据源的相关信息
package pers.mobian;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
@SpringBootTest
class Springboot04ApplicationTests {
@Autowired
DataSource dataSource;
@Test
void contextLoads() throws SQLException {
//查看默认的数据源
System.out.println(dataSource.getClass());
//获得数据库连接
Connection connection = dataSource.getConnection();
System.out.println(connection);
//关闭数据库
connection.close();
}
}
测试结果:
//我们没有使用其他数据源,springboot就使用默认的数据源,且默认数据源是HikariDataSource
//HikariDataSource 号称 Java WEB 当前速度最快的数据源,相比于传统的 C3P0 、DBCP、Tomcat jdbc 等连接池更加优秀
class com.zaxxer.hikari.HikariDataSource
HikariProxyConnection@1375111241 wrapping com.mysql.cj.jdbc.ConnectionImpl@4eb9ae4d
数据源的所有默认配置类:DataSourceAutoConfiguration
Druid 是阿里巴巴开源平台上一个数据库连接池实现,结合了 C3P0、DBCP 等 DB 池的优点,同时加入了日志监控。
Druid 可以很好的监控 DB 池连接和 SQL 的执行情况,天生就是针对监控而生的 DB 连接池。
对应的maven依赖为,由于其日志是使用log4j,所以也需要引入日志对应的依赖
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>1.1.20version>
dependency>
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>1.2.17version>
dependency>
druid相关的参数
配置 | 缺省值 | 说明 |
---|---|---|
name | 配置这个属性的意义在于,如果存在多个数据源,监控的时候可以通过名字来区分。如果没有配置,将会生成一个名字,格式是:“DataSource-”+System.identifyHashCode(this) | |
url | 连接数据库的url,不同数据库不一样。例如:mysql:jdbc:mysql://10.20.153.104:3306/druid2 oracle:jdbc:oracle:thin:@10.20.149.85:1521:ocnauto | |
username | 连接数据库的用户名 | |
password | 连接数据库的密码。如果你不希望密码直接写在配置文件中,可以使用ConfigFilter | |
driverClassName | 根据url自动识别 | 这一项可配可不配,如果不配置druid会根据url自动识别dbType,然后选择相应的driverClassName |
initialSize | 0 | 初始化时建立物理连接的个数。初始化发生在显示调用init方法,或者第一次getConnection时 |
maxActive | 8 | 最大连接池数量 |
maxldle | 8 | 已经不再使用,配置了也没有效果 |
minldle | 最想连接池数量 | |
maxWait | 获取连接时最大等待时间,单位毫秒。配置了maxWait之后,缺省启用公平锁,并发效率有所下降,如果需要可以通过配置useUnfairLock属性为true使用非公平锁 | |
poolPreparedStatements | false | 是否缓存preparedStatement,也就是PSCache。PSCache对支持游戏的数据库性能提升巨大,比如说oracle。在mysql下建议关闭 |
maxOpenPreparedStatements | -1 | 要启用PSCache,必须配置大于0,当大于0时,poolPreparedStatement自动出发修改为true。在druid中,不会存在Oracle下PSCache占用内存过多的问题,可以把这个数值配置大一些,比如100 |
validationQuery | 用来检测连接是否有效的sql,要求时一个查询语句。如果validationQuery为null,testOnBorrow、testOnReturn、testWhileldle都不会起作用 | |
validationQueryTimeout | 单位秒,检测连接是否有效的超长时间。底层调用jdbcStatement对象的void setQueryTimeout(int seconds)方法 | |
testOnBorrow | true | 申请连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能 |
testOnReturn | false | 归还连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能 |
testWhileldle | false | 建议配置为true,不影响性能,并且保证安全性。申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效 |
timeBetweenEvictionRunsMillis | 一分钟 | 有两个含义:1)Destroy线程会检测连接的间隔时间,如果连接空闲时间大于等于minEvictionRunsMillis则关闭物理连接 2)testWhileldle的判断依据,详情看testWhileldle属性说明 |
numTestsPerEvictionRun | 不再使用,一个DruidDataSource只支持一个EvictionRun | |
minEvictableldleTimeMillis | 30分钟 | 连接保持空闲而不被驱逐的最长时间 |
connectionInitSqls | 物理连接初始化的时候执行的sql | |
exceptionSorter | 根据dbType自动识别 | 当数据库抛出一些不可恢复的异常时,抛弃连接 |
filters | 属性类型是字符串,通过别名的方式配置扩展插件,常用的插件有:监控统计用的filter:start日志用的filter:log4j 防御sql注入的filter:wall | |
proxyFilters | 类型是List |
在springboot启动类的统计目录下新建一个配置配:
@Configuration
public class DruidConfig {
/*
将自定义的 Druid数据源添加到容器中,不再让 Spring Boot 自动创建
绑定全局配置文件中的 druid 数据源属性到 com.alibaba.druid.pool.DruidDataSource从而让它们生效
@ConfigurationProperties(prefix = "spring.datasource"):作用就是将 全局配置文件中
前缀为 spring.datasource的属性值注入到 com.alibaba.druid.pool.DruidDataSource 的同名参数中
*/
@Bean
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource druidDataSource() {
return new DruidDataSource();
}
}
测试类:
@SpringBootTest
class Springboot04ApplicationTests {
@Autowired
DataSource dataSource;
@Test
void contextLoads() throws SQLException {
//查看默认的数据源
System.out.println(dataSource.getClass());
//获得数据库连接
Connection connection = dataSource.getConnection();
System.out.println(connection);
DruidDataSource druidDataSource = (DruidDataSource) dataSource;
System.out.println("druidDataSource 数据源最大连接数:" + druidDataSource.getMaxActive());
System.out.println("druidDataSource 数据源初始化连接数:" + druidDataSource.getInitialSize());
//关闭数据库
connection.close();
}
}
测试结果:
class com.alibaba.druid.pool.DruidDataSource
2020-03-17 20:56:55.105 INFO 10448 --- [ main] com.alibaba.druid.pool.DruidDataSource : {dataSource-1} inited
com.mysql.cj.jdbc.ConnectionImpl@25ce435
druidDataSource 数据源最大连接数:8
druidDataSource 数据源初始化连接数:0
在yaml核心配置文件中进行相应设置后
spring:
datasource:
username: root
password:
#?serverTimezone=UTC解决时区的报错
url: jdbc:mysql://localhost:3306/mybatis?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
再次测试结果:
class com.alibaba.druid.pool.DruidDataSource
log4j:WARN No appenders could be found for logger (druid.sql.Connection).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
2020-03-17 20:59:36.003 INFO 1964 --- [ main] com.alibaba.druid.pool.DruidDataSource : {dataSource-1} inited
com.alibaba.druid.proxy.jdbc.ConnectionProxyImpl@4cb00fa5
druidDataSource 数据源最大连接数:20
druidDataSource 数据源初始化连接数:5 //在配置文件中进行了修改
Druid 数据源具有监控的功能,并提供了一个 web 界面方便用户查看,类似安装 路由器 时,人家也提供了一个默认的 web 页面
对应的配置类
package pers.mobian.config;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
@Configuration
public class DruidConfig {
/*
将自定义的 Druid数据源添加到容器中,不再让 Spring Boot 自动创建
绑定全局配置文件中的 druid 数据源属性到 com.alibaba.druid.pool.DruidDataSource从而让它们生效
@ConfigurationProperties(prefix = "spring.datasource"):作用就是将 全局配置文件中
前缀为 spring.datasource的属性值注入到 com.alibaba.druid.pool.DruidDataSource 的同名参数中
*/
@Bean
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource druidDataSource() {
return new DruidDataSource();
}
//配置 Druid 监控管理后台的Servlet;
//内置 Servlet 容器时没有web.xml文件,所以使用 Spring Boot 的注册 Servlet 方式
@Bean
public ServletRegistrationBean statViewServlet() {
ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
// 这些参数可以在 com.alibaba.druid.support.http.StatViewServlet
// 的父类 com.alibaba.druid.support.http.ResourceServlet 中找到
Map<String, String> initParams = new HashMap<>();
initParams.put("loginUsername", "admin"); //后台管理界面的登录账号
initParams.put("loginPassword", "123456"); //后台管理界面的登录密码
//后台允许谁可以访问
//initParams.put("allow", "localhost"):表示只有本机可以访问
//initParams.put("allow", ""):为空或者为null时,表示允许所有访问
initParams.put("allow", "");
//deny:Druid 后台拒绝谁访问
//initParams.put("kuangshen", "192.168.1.20");表示禁止此ip访问
//设置初始化参数
bean.setInitParameters(initParams);
return bean;
}
}
在url中访问:http://localhost:8080/druid 它会自动跳转到http://localhost:8080/druid/login.html
在正确输入用户名和密码后,可以进入到其对应的后台。当用户进行了相关操作以后,其后台就会打印与其相关的信息。(此截图为我新开的一个界面,执行了相应的映射语句后,该监控后台打印出我的操作的sql语句)
//配置 Druid 监控 之 web 监控的 filter
//WebStatFilter:用于配置Web和Druid数据源之间的管理关联监控统计
@Bean
public FilterRegistrationBean webStatFilter() {
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(new WebStatFilter());
//exclusions:设置哪些请求进行过滤排除掉,从而不进行统计
Map<String, String> initParams = new HashMap<>();
initParams.put("exclusions", "*.js,*.css,/druid/*,/jdbc/*");
bean.setInitParameters(initParams);
//"/*" 表示过滤所有请求
bean.setUrlPatterns(Arrays.asList("/*"));
return bean;
}
在进行该步操作时,创建的SpringBoot项目需要的依赖是:JDBC API 、MySQL Driver
还需要引入springboot与mybatis相关联的依赖
<dependency>
<groupId>org.mybatis.spring.bootgroupId>
<artifactId>mybatis-spring-boot-starterartifactId>
<version>2.1.1version>
dependency>
由于需要启动web服务,所以还需要引入web的启动器
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
为了代码方便引入lombok插件依赖
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<version>1.18.8version>
<scope>providedscope>
dependency>
整合案例步骤:
1、连接数据库
spring:
datasource:
username: root
password:
#?serverTimezone=UTC解决时区的报错
url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
driver-class-name: com.mysql.cj.jdbc.Driver
#此处配置文件可以当作mybatis的配置类,可以配置实体类的别名,以及映射文件的位置
mybatis:
type-aliases-package: pers.mobian.pojo #别名
mapper-locations: mapper/*.xml #mapper类的位置,mybatis配置类中的绑定mapper语句
2、编写对应的实体类
package pers.mobian.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private String name;
private int id;
private String pwd;
}
3、编写对应的接口类
package pers.mobian.mapper;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import pers.mobian.pojo.User;
import java.util.List;
@Repository
@Mapper
public interface UserMapper {
//查询所有的用户
List<User> selectUser();
//根据id查询用户
User selectUserById(int id);
//添加用户
public int insertUser(User user);
//删除用户
public int deleteUser(int id);
//修改用户
public int updateUser(User user);
}
4、编写对应的接口的mapper类
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="pers.mobian.mapper.UserMapper">
<select id="selectUser" parameterType="pers.mobian.pojo.User" resultType="pers.mobian.pojo.User">
select * from mybatis.user
</select>
<select id="selectUserById" resultType="pers.mobian.pojo.User">
select * from mybatis.user where id=#{id}
</select>
<insert id="insertUser" parameterType="pers.mobian.pojo.User">
insert into mybatis.user (name,id,pwd) values (#{name},#{id},#{pwd})
</insert>
<delete id="deleteUser" parameterType="int">
delete from mybatis.user where id=#{id}
</delete>
<update id="updateUser" parameterType="pers.mobian.pojo.User">
update mybatis.user set name=#{name},id=#{id},pwd=#{pwd} where id=#{id}
</update>
</mapper>
5、对应的控制器类
package pers.mobian.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import pers.mobian.mapper.UserMapper;
import pers.mobian.pojo.User;
import java.util.List;
@RestController
public class UserTest {
//自动装配UserMapper
@Autowired
private UserMapper userMapper;
@RequestMapping("/selectUser")
public List<User> selectUserTest() {
List<User> userList = userMapper.selectUser();
for (User user : userList) {
System.out.println(user);
}
return userList;
}
@RequestMapping("/selectUser/{id}")
public User selectUserById(@PathVariable("id") int id) {
User user = userMapper.selectUserById(id);
System.out.println(user);
return user;
}
@RequestMapping("/insertUser")
public String insertUser() {
userMapper.insertUser(new User("王二小", 1, "999"));
return "insertUser ok";
}
@RequestMapping("/deleteUser/{id}")
public String deleteUser(@PathVariable("id") int id) {
userMapper.deleteUser(id);
return "deleteUser ok";
}
@RequestMapping("/updateUser")
public String updateUser(){
userMapper.updateUser(new User("王三小",1,"jjjj"));
return "updateUser ok";
}
}
注意:接口类与其的对应的mapper类如果没有在同一目录下,则在yaml核心配置文件中需要进行相应的绑定。类似于曾经mybatis-config配置文件中定位资源文件。
基于AOP技术的安全
属于非功能性需求,但应在设计之初就考虑
Spring Security是针对Spring项目的安全框架,也是Spring Boot底层安全模块默认的技术选型,它可以实现强大的Web安全控制,对于安全控制,我们仅需要引入spring-boot-starter-security模块,进行少量的配置,即可实现强大的安全管理
需要记忆的几个类:
Spring Security的两个主要目标是“认证”和“授权”(控制访问)
认证:Authentication
授权:Authorization
这是两个通用的概念,不仅仅在Spring Security中存在
重写configure(HttpSecurity http)方法
http.xxx可以设置相应的权限规则
Spring Security拥有自己定制的登录界面,如果需要使用自己的,要进行相应的设置
还可以自己开启相关的操作,如:记住次此会话(cookie,默认保存两周)、注销功能、开启csrf防止网站被恶意攻击
1、导入依赖
<dependency>
<groupId>org.apache.shirogroupId>
<artifactId>shiro-coreartifactId>
<version>1.4.2version>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>jcl-over-slf4jartifactId>
<version>1.7.21version>
<scope>runtimescope>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>slf4j-log4j12artifactId>
<version>1.7.21version>
<scope>runtimescope>
dependency>
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>1.2.17version>
<scope>runtimescope>
dependency>
2、在resource目录下新建log4j.properties
log4j.rootLogger=INFO, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m %n
# General Apache libraries
log4j.logger.org.apache=WARN
# Spring
log4j.logger.org.springframework=WARN
# Default Shiro logging
log4j.logger.org.apache.shiro=INFO
# Disable verbose logging
log4j.logger.org.apache.shiro.util.ThreadContext=WARN
log4j.logger.org.apache.shiro.cache.ehcache.EhCache=WARN
3、在resource目录下新建shiro.ini
[users]
# user 'root' with password 'secret' and the 'admin' role
root = secret, admin
# user 'guest' with the password 'guest' and the 'guest' role
guest = guest, guest
# user 'presidentskroob' with password '12345' ("That's the same combination on
# my luggage!!!" ;)), and role 'president'
presidentskroob = 12345, president
# user 'darkhelmet' with password 'ludicrousspeed' and roles 'darklord' and 'schwartz'
darkhelmet = ludicrousspeed, darklord, schwartz
# user 'lonestarr' with password 'vespa' and roles 'goodguy' and 'schwartz'
lonestarr = vespa, goodguy, schwartz
# -----------------------------------------------------------------------------
# Roles with assigned permissions
#
# Each line conforms to the format defined in the
# org.apache.shiro.realm.text.TextConfigurationRealm#setRoleDefinitions JavaDoc
# -----------------------------------------------------------------------------
[roles]
# 'admin' role has all permissions, indicated by the wildcard '*'
admin = *
# The 'schwartz' role can do anything (*) with any lightsaber:
schwartz = lightsaber:*
# The 'goodguy' role is allowed to 'drive' (action) the winnebago (type) with
# license plate 'eagle5' (instance specific id)
goodguy = winnebago:drive:eagle5
4、新建一个快速的开始类Quickstart
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Simple Quickstart application showing how to use Shiro's API.
*
* @since 0.9 RC2
*/
public class Quickstart {
private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class);
public static void main(String[] args) {
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
SecurityManager securityManager = factory.getInstance();
SecurityUtils.setSecurityManager(securityManager);
// get the currently executing user:
//获得当前的用户对象Subject
Subject currentUser = SecurityUtils.getSubject();
// Do some stuff with a Session (no need for a web or EJB container!!!)
//通过当前的用户对象拿到Session
Session session = currentUser.getSession();
session.setAttribute("someKey", "aValue");
String value = (String) session.getAttribute("someKey");
if (value.equals("aValue")) {
log.info("Retrieved the correct value! [" + value + "]");
}
// let's login the current user so we can check against roles and permissions:
//判断当前用户是否被认证
if (!currentUser.isAuthenticated()) {
//Token:令牌,随机
UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
token.setRememberMe(true);//设置记住我
try {
currentUser.login(token);//执行登录操作
} catch (UnknownAccountException uae) {
log.info("There is no user with username of " + token.getPrincipal());
} catch (IncorrectCredentialsException ice) {
log.info("Password for account " + token.getPrincipal() + " was incorrect!");
} catch (LockedAccountException lae) {
log.info("The account for username " + token.getPrincipal() + " is locked. " +
"Please contact your administrator to unlock it.");
}
// ... catch more exceptions here (maybe custom ones specific to your application?
catch (AuthenticationException ae) {
//unexpected condition? error?
}
}
//say who they are:
//print their identifying principal (in this case, a username):
log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");
//test a role:
if (currentUser.hasRole("schwartz")) {
log.info("May the Schwartz be with you!");
} else {
log.info("Hello, mere mortal.");
}
//test a typed permission (not instance-level)
//粗粒度
if (currentUser.isPermitted("lightsaber:wield")) {
log.info("You may use a lightsaber ring. Use it wisely.");
} else {
log.info("Sorry, lightsaber rings are for schwartz masters only.");
}
//a (very powerful) Instance Level permission:
//细粒度
if (currentUser.isPermitted("winnebago:drive:eagle5")) {
log.info("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'. " +
"Here are the keys - have fun!");
} else {
log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
}
//all done - log out!
//注销
currentUser.logout();
//结束
System.exit(0);
}
}
执行结果:
2020-03-18 15:43:58,561 INFO [org.apache.shiro.session.mgt.AbstractValidatingSessionManager] - Enabling session validation scheduler...
2020-03-18 15:43:59,783 INFO [Quickstart] - Retrieved the correct value! [aValue]
2020-03-18 15:43:59,787 INFO [Quickstart] - User [lonestarr] logged in successfully.
2020-03-18 15:43:59,787 INFO [Quickstart] - May the Schwartz be with you!
2020-03-18 15:43:59,788 INFO [Quickstart] - You may use a lightsaber ring. Use it wisely.
2020-03-18 15:43:59,788 INFO [Quickstart] - You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'. Here are the keys - have fun!
核心要点:
Subject currentUser = SecurityUtils.getSubject();
Session session = currentUser.getSession();
currentUser.isAuthenticated()
currentUser.hasRole("schwartz")
currentUser.isPermitted("lightsaber:wield")
currentUser.logout();
currentUser.getPrincipal()
1、新建一个带web依赖的springboot项目
2、引入外部依赖:shiro-spring与thymeleaf模板引擎需要的依赖
<dependency>
<groupId>org.apache.shirogroupId>
<artifactId>shiro-springartifactId>
<version>1.4.2version>
dependency>
<dependency>
<groupId>org.thymeleafgroupId>
<artifactId>thymeleaf-spring5artifactId>
dependency>
<dependency>
<groupId>org.thymeleaf.extrasgroupId>
<artifactId>thymeleaf-extras-java8timeartifactId>
dependency>
3、在配置包下新建UserRealm类
package pers.mobian.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;
public class UserRealm extends AuthorizingRealm {
//授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
System.out.println("执行了=> 授权doGetAuthorizationInfo");
return null;
}
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("执行了=> 认证doGetAuthenticationInfo");
return null;
}
}
4、在配置包下新建ShiroConfig类
package pers.mobian.config;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ShiroConfig {
//创建ShiroFilterFactoryBean
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultSecurityManager defaultSecurityManager) {
ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
//设置安全管理器
bean.setSecurityManager(defaultSecurityManager);
return bean;
}
//创建DefaultSecurityManager
@Bean(name = "securityManager")
public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm) {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
//关联userRealm
securityManager.setRealm(userRealm);
return securityManager;
}
//创建realm对象, 需要自定义类
@Bean
public UserRealm userRealm() {
return new UserRealm();
}
}
5、新建控制器类IndexController
package pers.mobian.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class IndexController {
@RequestMapping({"/", "/index"})
public String indexTest(Model model) {
model.addAttribute("msg", "hello springboot-shiro");
return "index";
}
@RequestMapping("/user/add")
public String addTest(){
return "/user/add";
}
@RequestMapping("/user/update")
public String updateTest(){
return "/user/update";
}
}
6、在templates目录下编写html界面
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Titletitle>
head>
<body>
<h1>首页h1>
<p th:text="${msg}">p>
<a th:href="@{/user/add}">adda>|<a th:href="@{/user/update}">updatea>
body>
html>
7、在templates下新建user目录,并建立add.html和update.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>add</h1>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>update</h1>
</body>
</html>
8、测试结果
1、修改ShiroConfig类
package pers.mobian.config;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.LinkedHashMap;
import java.util.Map;
@Configuration
public class ShiroConfig {
//创建ShiroFilterFactoryBean
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultSecurityManager defaultSecurityManager) {
ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
//设置安全管理器
bean.setSecurityManager(defaultSecurityManager);
//添加shiro的内置过滤器
/*
anno:无需认证就可以访问
authc:必须认证了才能通过
user:必须拥有记住我这个功能才能使用
perms:拥有对某个资源的权限才能访问
role:拥有某个角色权限才能访问
*/
Map<String, String> filterMap = new LinkedHashMap<>();
filterMap.put("/user/*","authc");
bean.setFilterChainDefinitionMap(filterMap);
//设置登录的请求
bean.setLoginUrl("/toLogin");
return bean;
}
//创建DefaultSecurityManager
@Bean(name = "securityManager")
public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm) {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
//关联userRealm
securityManager.setRealm(userRealm);
return securityManager;
}
//创建realm对象, 需要自定义类
@Bean
public UserRealm userRealm() {
return new UserRealm();
}
}
2、新建一个登录界面
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
head>
<body>
<form action="">
<p>用户名:<input type="text" name="username">p>
<p>密码:<input type="password" name="password">p>
<p><input type="submit">p>
form>
body>
html>
3、添加对应的映射
@RequestMapping("/toLogin")
public String toLogin(){
return "login";
}
测试点击对应的方法,会跳转到登录界面
1、在控制器类中添加对应的代码
@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";
}
}
2、修改UserRealm
package pers.mobian.config;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
public class UserRealm extends AuthorizingRealm {
//授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
System.out.println("执行了=> 授权doGetAuthorizationInfo");
return null;
}
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("执行了=> 认证doGetAuthenticationInfo");
//用户名,密码,来自于数据库中取出,此处伪造数据
String name="root";
String password = "123456";
UsernamePasswordToken userToken = (UsernamePasswordToken) token;
if(!userToken.getUsername().equals(name)){
return null;//抛出异常 UnknownAccountException(控制器中定义的异常)
}
//密码认证,shiro自己内部操作
return new SimpleAuthenticationInfo("",password,"");
}
}
3、此时即可完成用户身份的校验
每次登录的时候,系统都会去通过控制器类然后跳转到UserRealm类,继而进行用户名和密码的判断。
1、引入对应的maven依赖
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>1.1.20version>
dependency>
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>1.2.17version>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<version>1.18.8version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.16version>
dependency>
<dependency>
<groupId>org.mybatis.spring.bootgroupId>
<artifactId>mybatis-spring-boot-starterartifactId>
<version>2.1.1version>
dependency>
<dependency>
<groupId>org.apache.shirogroupId>
<artifactId>shiro-springartifactId>
<version>1.4.2version>
dependency>
2、新建核心配置文件application.yaml,用来配置数据源(可以自行选择添加与否)并且配置mybatis信息
spring:
datasource:
username: root
password:
#?serverTimezone=UTC解决时区的报错
url: jdbc:mysql://localhost:3306/mybatis?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
mybatis:
type-aliases-package: pers.mobian.pojo
mapper-locations: classpath:mapper/*.xml
3、新建实体类
package pers.mobian.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private String name;
private int id;
private String pwd;
}
4、新建mapper的接口类
package pers.mobian.mapper;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import pers.mobian.pojo.User;
@Mapper
@Repository
public interface UserMapper {
public User queryUserByName(String name);
}
5、新建mapper接口类的实体类
<mapper namespace="pers.mobian.mapper.UserMapper">
<select id="queryUserByName" parameterType="String" resultType="User">
select * from mybatis.user where name=#{name}
select>
mapper>
6、编写对应的service层接口类
package pers.mobian.service;
import pers.mobian.pojo.User;
public interface UserService {
public User queryUserByName(String name);
}
7、编写对应的service层接口类的实现类
package pers.mobian.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pers.mobian.mapper.UserMapper;
import pers.mobian.pojo.User;
@Service
public class UserServiceImpl implements UserService{
@Autowired
UserMapper userMapper;
@Override
public User queryUserByName(String name) {
return userMapper.queryUserByName(name);
}
}
8、控制器类代码不变
@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";
}
}
9、ShiroConfig类不变
package pers.mobian.config;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.LinkedHashMap;
import java.util.Map;
@Configuration
public class ShiroConfig {
//创建ShiroFilterFactoryBean
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultSecurityManager defaultSecurityManager) {
ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
//设置安全管理器
bean.setSecurityManager(defaultSecurityManager);
//添加shiro的内置过滤器
/*
anno:无需认证就可以访问
authc:必须认证了才能通过
user:必须拥有记住我这个功能才能使用
perms:拥有对某个资源的权限才能访问
role:拥有某个角色权限才能访问
*/
Map<String, String> filterMap = new LinkedHashMap<>();
filterMap.put("/user/*","authc");
bean.setFilterChainDefinitionMap(filterMap);
//设置登录的请求
bean.setLoginUrl("/toLogin");
return bean;
}
//创建DefaultSecurityManager
@Bean(name = "securityManager")
public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm) {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
//关联userRealm
securityManager.setRealm(userRealm);
return securityManager;
}
//创建realm对象, 需要自定义类
@Bean
public UserRealm userRealm() {
return new UserRealm();
}
}
10、将UserRealm类中的模拟数据变成真实的数据库数据
package pers.mobian.config;
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.springframework.beans.factory.annotation.Autowired;
import pers.mobian.pojo.User;
import pers.mobian.service.UserService;
public class UserRealm extends AuthorizingRealm {
@Autowired
UserService userService;
//授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
System.out.println("执行了=> 授权doGetAuthorizationInfo");
return null;
}
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("执行了=> 认证doGetAuthenticationInfo");
UsernamePasswordToken userToken = (UsernamePasswordToken) token;
//连接真实的数据库
User user = userService.queryUserByName(userToken.getUsername());
if(user == null) { //数据库中没有查询到该用户
return null;
}
//md5加密:一串数字
//md5盐值加密:一串数字加上用户名
//密码认证,shiro自己操作
return new SimpleAuthenticationInfo("",user.getPwd(),"");
}
}
11、对应的目录结构是
12、测试代码即可完成安全验证
type=Unauthorized,status=401
1、修改数据库的字段并且修改pojo类
2、修改ShiroConfig类
package pers.mobian.config;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.LinkedHashMap;
import java.util.Map;
@Configuration
public class ShiroConfig {
//创建ShiroFilterFactoryBean
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultSecurityManager defaultSecurityManager) {
ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
//设置安全管理器
bean.setSecurityManager(defaultSecurityManager);
//添加shiro的内置过滤器
/*
anno:无需认证就可以访问
authc:必须认证了才能通过
user:必须拥有记住我这个功能才能使用
perms:拥有对某个资源的权限才能访问
role:拥有某个角色权限才能访问
*/
//拦截
Map<String, String> filterMap = new LinkedHashMap<>();
//授权,正常情况下,没有授权会跳转到未授权页面
filterMap.put("/user/add","perms[user:add]");
filterMap.put("/user/update","perms[user:update]");
filterMap.put("/user/*","authc");
bean.setFilterChainDefinitionMap(filterMap);
//设置登录的请求
bean.setLoginUrl("/toLogin");
//未授权的页面
bean.setUnauthorizedUrl("/unauthorized");
return bean;
}
//创建DefaultSecurityManager
@Bean(name = "securityManager")
public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm) {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
//关联userRealm
securityManager.setRealm(userRealm);
return securityManager;
}
//创建realm对象, 需要自定义类
@Bean
public UserRealm userRealm() {
return new UserRealm();
}
}
3、修改UserRealm类
package pers.mobian.config;
import org.apache.catalina.security.SecurityUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
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.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import pers.mobian.pojo.User;
import pers.mobian.service.UserService;
public class UserRealm extends AuthorizingRealm {
@Autowired
UserService userService;
//授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
System.out.println("执行了=> 授权doGetAuthorizationInfo");
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
info.addStringPermission("user:add");
//拿到当前登录的这个对象
Subject subject = SecurityUtils.getSubject();
//拿到User对象
User currentUser = (User) subject.getPrincipal();
//设置当前用户的权限
info.addStringPermission(currentUser.getPerms());
return info;
}
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("执行了=> 认证doGetAuthenticationInfo");
UsernamePasswordToken userToken = (UsernamePasswordToken) token;
//连接真实的数据库
User user = userService.queryUserByName(userToken.getUsername());
if(user == null) { //数据库中没有查询到该用户
return null;
}
//md5加密:一串数字
//md5盐值加密:一串数字加上用户名
//密码认证,shiro自己操作
return new SimpleAuthenticationInfo("user",user.getPwd(),"");
}
}
此案例能够达到不同的用户对同一个页面拥有不同的权限
目的:将Shiro与前端的模板引擎Thymeleaf整合,达到不同权限不同显示的效果
1、修改index.html界面
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml"
xmlns:shiro="http://www.thymeleaf.org/thymeleaf-extras-shiro">
<head>
<meta charset="UTF-8">
<title>Titletitle>
head>
<body>
<h1>首页h1>
<div th:if="${session.loginUser==null}">
<a th:href="@{/toLogin}">登录a>
div>
<p th:text="${msg}">p>
<div shiro:hasPermission="user:add">
<a th:href="@{/user/add}">adda>
div>
<div shiro:hasPermission="user:update">
<a th:href="@{/user/update}">updatea>
div>
body>
html>
2、将前端需要的session放在UserRealm类中
package pers.mobian.config;
import org.apache.catalina.security.SecurityUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import pers.mobian.pojo.User;
import pers.mobian.service.UserService;
public class UserRealm extends AuthorizingRealm {
@Autowired
UserService userService;
//授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
System.out.println("执行了=> 授权doGetAuthorizationInfo");
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
info.addStringPermission("user:add");
//拿到当前登录的这个对象
Subject subject = SecurityUtils.getSubject();
//拿到User对象
User currentUser = (User) subject.getPrincipal();
//设置当前用户的权限
info.addStringPermission(currentUser.getPerms());
return info;
}
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("执行了=> 认证doGetAuthenticationInfo");
UsernamePasswordToken userToken = (UsernamePasswordToken) token;
//连接真实的数据库
User user = userService.queryUserByName(userToken.getUsername());
if(user == null) { //数据库中没有查询到该用户
return null;
}
Subject currentSubject = SecurityUtils.getSubject();
Session session = currentSubject.getSession();
session.setAttribute("loginUser",user);
//md5加密:一串数字
//md5盐值加密:一串数字加上用户名
//密码认证,shiro自己操作
return new SimpleAuthenticationInfo("user",user.getPwd(),"");
}
}