<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
启动器: 说白了就是SpringBoot的启动场景;
比如spring-boot-starter-web, 它就会帮我们导入web环境所有的依赖
SpringBoot会将所有的功能场景, 都变成一个个的启动器
我们要使用什么功能, 就只需找到对应的启动器就可以了 starter
//标注这个类是一个SpringBoot的应用
@SpringBootApplication
public class SpringbootStudyApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootStudyApplication.class, args);
}
}
注解
@SpringBootConfiguration: SpringBoot的配置
@Configuration: Spring配置类
@Component: 说明这也是Spring的一个组件
@EnableAutoConfiguration: 自动配置
@AutoConfigurationPackage: 自动配置包
@Import({Registrar.class}): 导入注册类
@Import({AutoConfigurationImportSelector.class}): 自动配置导入选择器
配置文件的作用: 修改SpringBoot自动配置的默认值, 因为SpringBoot在底层都给我们自动配置好了
#对空格要求很严格 冒号后要加一个空格
#普通的key: value
name: 张三
#对象
student:
name: 张三
age: 18
#行内写法
student: {name: 张三,age: 18}
#数组
pet:
- cat
- dog
- pig
#行内写法
pet: [cat,dog,pig]
传统的注解方式 @Component + @Value
@Component
public class Person {
@Value("张三")
private String name;
//省略...
}
使用注解@Component + @ConfigurationProperties(prefix = "person")的方式, 把.yaml配置文件中的属性映射到这个组件中, prefix = "person" 表示将配置文件中person下的所有属性一一对应 [推荐]
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
private String name;
private Integer age;
private Boolean happy;
private Date birth;
private Map<String, Object> map;
private List<Object> list;
private Dog dog;
//Getter and Setter
}
#yaml配置文件
#key: value 冒号后面要有一个空格
#对空格要求很严格
person:
name: 张三
age: 18
happy: false
birth: 2000/01/01
map: {k1: v1,k2: v2}
list: [code,music,girl]
dog:
name: 小黑
age: 2
使用注解@Component + @PropertySource(value = "classpath:zhangsan.properties")绑定自定义的.properties文件, 然后需要在实体类中的属性上方使用SPEL表达式取出配置文件的值比如 @Value("${name}"), 比较麻烦
@Component
@PropertySource(value = "classpath:zhangsan.properties")
public class Person {
@Value("${name}")
private String name;
//省略...
}
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
@Component
@ConfigurationProperties(prefix = "dog")
public class Dog {
private String name;
private Integer age;
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
private LocalDate birth;
//省略...
}
#yaml
dog: {name: 小黄,age: 2,birth: 2020-01-01}
如果我们使用的是properties配置文件, 需要设置idea编码格式为UTF-8, idea中默认的编码格式为GBK, 修改为UTF-8以防止乱码
Settings > Editor > File Encoding中把所有的编码格式改为UTF-8, 最后一个可以打钩
JSR303数据校验, 这个就是我们可以在字段上增加一层过滤器验证, 可以保证数据的合法性
需要导入依赖到pom.xml中
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
类上方使用注解@Validated 开启数据校验
@Component
@ConfigurationProperties(prefix = "person")
@Validated //数据校验
public class Person {
@Email(message = "邮箱格式错误!")
private String name;
//省略...
}
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
server:
port: 8080
spring:
profiles:
active: test
---
server:
port: 8082
spring:
profiles: dev
---
server:
port: 8084
spring:
profiles: test
xxxAutoConfiguration: 自动配置类, 给容器中添加组件
xxxProperties: 封装配置文件中相关属性
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.6.0</version>
</dependency>
http://localhost:8080/webjars/jquery/3.6.0/jquery.js 可以访问到jquery.js
双击shift,找到WebMvcAutoConfiguration.class
总结:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!--所有的html元素都可以被 thymeleaf替换接管: th: 元素名-->
<!--转义,非转义-->
<!--<h1>hello SpringBoot!</h1>-->
<div th:text="${msg}"></div>
<!--hello SpringBoot!-->
<div th:utext="${msg}"></div>
<hr>
<!--遍历集合-->
<h3 th:each="user:${users}" th:text="${user}"></h3>
</body>
</html>
package com.dz.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.Arrays;
//在templates目录下的所有页面, 只能通过controller访问
//这个需要模板引擎的支持 thymeleaf
@Controller
public class IndexController {
@RequestMapping("/test")
public String index(Model model) {
model.addAttribute("msg","<h1>hello SpringBoot!</h1>");
model.addAttribute("users", Arrays.asList("张三","李四"));
return "test";
}
}
package com.dz.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 java.util.Locale;
//如果向diy一些定制化的功能, 只要写这个组件,然后将它交给SpringBoot ,SpringBoot就帮我们自动装配
//扩展SpringMVC dispatcherServlet
@Configuration
public class MyMvcConfig {
//ViewResolver 实现了视图解析器接口的类, 我们就可以把它看做视图解析器
@Bean
public ViewResolver myViewResolver() {
return new MyViewResolver();
}
//自定义了一个自己的视图解析器MyViewResolver
public static class MyViewResolver implements ViewResolver {
@Override
public View resolveViewName(String s, Locale locale) throws Exception {
return null;
}
}
}
package com.dz.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
//如果我们要扩展SpringMVC 官方建议我们这样去做
@Configuration
@EnableWebMvc //这个就是导入了一个类DelegatingWebMvcConfiguration, 从容器中获取所有的webmvcconfig
public class MyMvcConfig implements WebMvcConfigurer {
//视图跳转
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/dz").setViewName("test");
}
}
package com.dz.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
//如果我们要扩展SpringMVC 官方建议我们这样去做
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
registry.addViewController("/login.html").setViewName("login");
}
}
resources目录下创建 i18n目录, 在 i18n目录 下新建login.properties文件, 再创建login_zh_CN.properties文件(中文), 现在这两个目录被自动整合在Resource Bundle ‘login‘目录下, 在此目录下再新建login_en_US.properties (英文)
在login.html< html >标签里导入xmlns:th="http://www.thymeleaf.org" , 就可以使用thymeleaf模板了
页面国际化
需要配置 i18n 文件(在application.properties中)
#关闭模板引擎的缓存
spring.thymeleaf.cache=false
#项目路径设置
server.servlet.context-path=/dz
#我们的配置文件放在的真实位置
spring.messages.basename=i18n.login
如果需要项目中进行按钮自动切换, 需要自定义一个组件LocalResolver
记得将自己写的组件配置到Spring容器中 @Bean
从session中取值 [[${session.loginUser}]]
<!--web-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!--druid-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<!--log4j-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
package com.dz.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private int id;
private String username;
private String password;
private int gender;
private Date registerTime;
}
UserMapper.java
如果不使用@mapper注解,则需要在启动类上添加@MapperScan注解, 扫描Mapper接口所在的包
@MapperScan(basePackages = "com.dz.mapper")
package com.dz.mapper;
import com.dz.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import java.util.List;
@Mapper
@Repository
public interface UserMapper {
List<User> findAll();
}
<?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.dz.mapper.UserMapper">
<resultMap id="user_resultMap" type="User">
<id column="id" property="id"/>
<result column="username" property="username"/>
<result column="password" property="password"/>
<result column="gender" property="gender"/>
<result column="register_time" property="registerTime"/>
</resultMap>
<select id="findAll" resultMap="user_resultMap">
select id,username,password,gender,register_time
from t_user
</select>
</mapper>
#MyBatis配置
mybatis:
mapper-locations: classpath:mapper/*.xml
type-aliases-package: com.dz.pojo
configuration:
map-underscore-to-camel-case: true
#连接数据库信息
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql:///mybatis_db?useUnicode=true&characterEncoding=utf8
username: root
password: 8031
type: com.alibaba.druid.pool.DruidDataSource
#SpringBoot默认是不注入这些属性值的, 需要自己绑定
#druid数据源专属配置
#初始化大小, 最大,最小
initialSize: 5
minIdle: 5
maxActive: 20
#配置获取连接等待超时的时间
maxWait: 60000
#配置间隔多久才进行一次检测, 检测需要关闭的空闲连接, 单位是毫秒
timeBetweenEvictionRunsMillis: 60000
#配置一个连接在池中最小生存的时间, 单位是毫秒
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT1FROMDUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
#配置监控统计拦截的filters, 去掉后监控界面sql无法统计, ‘wall‘用于防火墙
filters: stat,wall,log4j
#打开PSCache, 并且指定每个连接上PSCache的大小
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
#通过connectionProperties属性来打开mergeSql功能;慢SQL记录
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# MyBatis logging configuration
log4j.logger.org.mybatis.example.BlogMapper=TRACE
# 配置stdout输出到控制台
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
# 配置stdout设置为自定义布局模式
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
# 配置stdout日志的输出格式 2021-05-01 23:45:26,166 %p日志的优先级 %t线程名 %m日志 %n换行
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} - %5p [%t] - %m%n
package com.dz.config;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.servlet.Filter;
import javax.sql.DataSource;
import java.util.HashMap;
@Configuration
public class DruidConfig {
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druidDatasource(){
return new DruidDataSource();
}
//后台监控: 相当于web.xml
//SpringBoot内置了servlet容器, 所以没有web.xml, 替代方法: ServletRegistrationBean
@Bean
public ServletRegistrationBean StatViewServlet(){
ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
//后台需要有人登陆, 账号密码配置
HashMap<String, String> initParameters = new HashMap<>();
//增加配置
initParameters.put("loginUsername","admin"); //登陆的key 是固定的 loginUsername
initParameters.put("loginPassword","123456");// loginPassword
//允许谁可以访问
initParameters.put("allow","");
bean.setInitParameters(initParameters);//设置初始化参数
return bean;
}
//filter
@Bean
public FilterRegistrationBean webStatFilter(){
FilterRegistrationBean<Filter> bean = new FilterRegistrationBean<>();
bean.setFilter(new WebStatFilter());
//可以过滤哪些请求呢
HashMap<String, String> initParameters = new HashMap<>();
//这些不进行统计
initParameters.put("exclusions","*.js,*.css,/druid/*");
bean.setInitParameters(initParameters);
return bean;
}
}
<!--web-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--thymeleaf-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!--security-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!--thymeleaf-security整合包-->
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
<version>3.0.4.RELEASE</version>
</dependency>
这里面负责权限认证
开启注解@EnableWebSecurity
继承WebSecurityConfigurerAdapter
http为参数的是配置登录等相关参数的,auth为参数的是配置用户和权限的
package com.dz.config;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
//Aop: 拦截器
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
//授权
@Override
protected void configure(HttpSecurity http) throws Exception {
//首页所有人可以访问, 但是功能页只对有相关权限的人开启
//请求授权的规则
http.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/level1/**").hasRole("vip1")
.antMatchers("/level2/**").hasRole("vip2")
.antMatchers("/level3/**").hasRole("vip3");
//没有权限会跳到登陆页面, 需要开启登陆的页面
//定制登录页loginPage("/toLogin"), 把登陆的信息提交给我们默认页面Login让其进行判断
http.formLogin().loginPage("/toLogin")
.usernameParameter("user")//实际接收前端参数为user
.passwordParameter("pwd")//实际接收前端参数为pwd
.loginProcessingUrl("/login");//实际登陆路径
//开启了注销功能, 注销的同时同时删除cookie和session
http.logout().logoutSuccessUrl("/").deleteCookies().invalidateHttpSession(true);
//防止网站攻击: get post
http.csrf().disable();//关闭csrf功能,注销失败的原因
//开启记住我功能 cookie,默认保存两周, 自定义接收前端的参数为remember
http.rememberMe().rememberMeParameter("remember");
}
//认证
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//这些数据正常应该从数据库中读, 现在为了测试是在内存中读取
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("dz").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3")
.and()
.withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
.and()
.withUser("visitor").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
}
}
package com.dz.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class RouterController {
@RequestMapping({"/","/index"})
public String index(){
return "index";
}
@RequestMapping("/toLogin")
public String toLogin(){
return "views/login";
}
@RequestMapping("/level1/{id}")
public String level1(@PathVariable("id") int id){
return "views/level1/"+id;
}
@RequestMapping("/level2/{id}")
public String level2(@PathVariable("id") int id){
return "views/level2/"+id;
}
@RequestMapping("/level3/{id}")
public String level3(@PathVariable("id") int id){
return "views/level3/"+id;
}
}
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<title>登录</title>
<!--semantic-ui-->
<link href="https://cdn.bootcss.com/semantic-ui/2.4.1/semantic.min.css" rel="stylesheet">
</head>
<body>
<!--主容器-->
<div class="ui container">
<div class="ui segment">
<div style="text-align: center">
<h1 class="header">登录</h1>
</div>
<div class="ui placeholder segment">
<div class="ui column very relaxed stackable grid">
<div class="column">
<div class="ui form">
<form th:action="@{/login}" method="post">
<div class="field">
<label>Username</label>
<div class="ui left icon input">
<input type="text" placeholder="Username" name="user">
<i class="user icon"></i>
</div>
</div>
<div class="field">
<label>Password</label>
<div class="ui left icon input">
<input type="password" name="pwd">
<i class="lock icon"></i>
</div>
</div>
<div class="field">
<input type="checkbox" name="remember"> 记住我
</div>
<input type="submit" class="ui blue submit button"/>
</form>
</div>
</div>
</div>
</div>
<div style="text-align: center">
<div class="ui label">
</i>注册
</div>
<br><br>
<small>blog.kuangstudy.com</small>
</div>
<div class="ui segment" style="text-align: center">
<h3>Spring Security Study by 秦疆</h3>
</div>
</div>
</div>
<script th:src="@{/qinjiang/js/jquery-3.1.1.min.js}"></script>
<script th:src="@{/qinjiang/js/semantic.min.js}"></script>
</body>
</html>
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<title>首页</title>
<!--semantic-ui-->
<link href="https://cdn.bootcss.com/semantic-ui/2.4.1/semantic.min.css" rel="stylesheet">
<link th:href="@{/qinjiang/css/qinstyle.css}" rel="stylesheet">
</head>
<body>
<!--主容器-->
<div class="ui container">
<div class="ui segment" id="index-header-nav" th:fragment="nav-menu">
<div class="ui secondary menu">
<a class="item" th:href="@{/index}">首页</a>
<!--登录注销-->
<div class="right menu">
<!--如果未登录: 显示登陆按钮-->
<div sec:authorize="!isAuthenticated()">
<a class="item" th:href="@{/toLogin}">
<i class="sign-in icon"></i> 登录
</a>
</div>
<!--如果已登陆:显示用户名+注销按钮-->
<div sec:authorize="isAuthenticated()">
<a class="item">
用户名: <span sec:authentication="name"></span>
<!--角色: <span sec:authentication="principal.getAuthorities()"></span>-->
</a>
</div>
<div sec:authorize="isAuthenticated()">
<a class="item" th:href="@{/logout}">
<i class="sign-out icon"></i> 注销
</a>
</div>
</div>
</div>
</div>
<div class="ui segment" style="text-align: center">
<h3>Spring Security Study by 秦疆</h3>
</div>
<div>
<br>
<div class="ui three column stackable grid">
<!--菜单根据用户的角色动态的实现-->
<div class="column" sec:authorize="hasRole(‘vip1‘)">
<div class="ui raised segment">
<div class="ui">
<div class="content">
<h5 class="content">Level 1</h5>
<hr>
<div><a th:href="@{/level1/1}"><i class="bullhorn icon"></i> Level-1-1</a></div>
<div><a th:href="@{/level1/2}"><i class="bullhorn icon"></i> Level-1-2</a></div>
<div><a th:href="@{/level1/3}"><i class="bullhorn icon"></i> Level-1-3</a></div>
</div>
</div>
</div>
</div>
<div class="column" sec:authorize="hasRole(‘vip2‘)">
<div class="ui raised segment">
<div class="ui">
<div class="content">
<h5 class="content">Level 2</h5>
<hr>
<div><a th:href="@{/level2/1}"><i class="bullhorn icon"></i> Level-2-1</a></div>
<div><a th:href="@{/level2/2}"><i class="bullhorn icon"></i> Level-2-2</a></div>
<div><a th:href="@{/level2/3}"><i class="bullhorn icon"></i> Level-2-3</a></div>
</div>
</div>
</div>
</div>
<div class="column" sec:authorize="hasRole(‘vip3‘)">
<div class="ui raised segment">
<div class="ui">
<div class="content">
<h5 class="content">Level 3</h5>
<hr>
<div><a th:href="@{/level3/1}"><i class="bullhorn icon"></i> Level-3-1</a></div>
<div><a th:href="@{/level3/2}"><i class="bullhorn icon"></i> Level-3-2</a></div>
<div><a th:href="@{/level3/3}"><i class="bullhorn icon"></i> Level-3-3</a></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script th:src="@{/qinjiang/js/jquery-3.1.1.min.js}"></script>
<script th:src="@{/qinjiang/js/semantic.min.js}"></script>
</body>
</html>
<!--shiro-spring-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.7.1</version>
</dependency>
package com.dz.config;
import com.dz.pojo.User;
import com.dz.service.UserService;
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;
//自定义的UserRealm 继承AuthorizingRealm
public class UserRealm extends AuthorizingRealm {
@Autowired
private UserService userService;
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("执行了授权=>doGetAuthorizationInfo");
return null;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
System.out.println("执行了认证=>doGetAuthenticationInfo");
UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;
//连接真实的数据库
User user = userService.queryUserByName(userToken.getUsername());
if (user==null){//不存在此用户
return null;//UnknownAccountException
}
//可以加密: MD5 md5盐值加密
//密码认证, shiro去做, 加密了
return new SimpleAuthenticationInfo("", user.getPassword(), "");
}
}
package com.dz.config;
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") DefaultWebSecurityManager defaultWebSecurityManager){
ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
//设置安全管理器
bean.setSecurityManager(defaultWebSecurityManager);
//添加shiro的内置过滤器
/*
* anon: 无需认证就可以访问
* authc: 必须认证后才能访问
* user: 必须拥有 记住我功能 才能使用
* perms: 拥有对某个资源的权限才能访问
* role: 拥有某个角色权限才能访问
* */
/*filterMap.put("/user/add","authc");
filterMap.put("/user/update","authc");*/
//拦截
Map<String, String> filterMap = new LinkedHashMap<>();
filterMap.put("/user/*","authc");
bean.setFilterChainDefinitionMap(filterMap);
//设置登陆的请求
bean.setLoginUrl("/toLogin");
return bean;
}
//DefaultWebSecurityManager
@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();
}
}
# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# MyBatis logging configuration
log4j.logger.org.mybatis.example.BlogMapper=TRACE
# 配置stdout输出到控制台
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
# 配置stdout设置为自定义布局模式
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
# 配置stdout日志的输出格式 %d{yyyy-MM-dd HH:mm:ss,SSS} %p日志的优先级 %t线程名 %c类的全限定名 %m日志 %n换行
log4j.appender.stdout.layout.ConversionPattern=%d - %5p [%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
原文:https://www.cnblogs.com/MRASdoubleZ/p/14806074.html