shiro(安全)
Shiro简介
什么是shiro
Apache Shiro 是一个Java的安全(权限)框架
Shiro 可以非常容易的开发出足够好的应用,其不仅可以用在JavaSE环境,也可以用在JavaEE环境。
Shiro可以完成,认证,授权,加密,会话管理,Web集成,缓存等。
Shiro安全框架简介
Apache Shiro是Java的一个安全框架。功能强大,使用简单的Java安全框架,它为开发人员提供一个直观而全面的认证,授权,加密及会话管理的解决方案。
实际上,Shiro的主要功能是管理应用程序中与安全相关的全部,同时尽可能支持多种实现方法。Shiro是建立在完善的接口驱动设计和面向对象原则之上的,支持各种自定义行为。Shiro提供的默认实现,使其能完成与其他安全框架同样的功能,这不也是我们一直努力想要得到的吗!
Apache Shiro相当简单,对比Spring Security,可能没有Spring Security做的功能强大,但是在实际工作时可能并不需要那么复杂的东西,所以使用小而简单的Shiro就足够了。对于它俩到底哪个好,这个不必纠结,能更简单的解决项目问题就好了。
Shiro可以做什么
● 验证用户身份 ● 用户访问控制,比如用户是否被赋予了某个角色;是否允许访问某些资源 ● 在任何环境都可以使用Session API,即使不是WEB项目或没有EJB容器 ● 事件响应(在身份验证,访问控制期间,或是session生命周期中) ● 集成多种用户信息数据源 ● SSO-单点登陆 ● Remember Me,记住我 ● Shiro尝试在任何应用环境下实现这些功能,而不依赖其他框架、容器或应用服务器。
Shiro的特色
Shiro可以非常容易的开发出足够好的应用,其不仅可以用在JavaSE环境,也可以用在JavaEE环境。Shiro可以帮助我们完成:认证、授权、加密、会话管理、与Web集成、缓存等。这不就是我们想要的嘛,而且Shiro的API也是非常简单;其基本功能点如下图所示:
四大基石----身份验证,授权,会话管理,加密
-
Authentication:身份认证/登录,验证用户是不是拥有相应的身份;
-
Authorization:授权,即权限验证,验证某个已认证的用户是否拥有某个权限;即判断用户是否能做事情,常见的如:验证某个用户是否拥有某个角色。或者细粒度的验证某个用户对某个资源是否具有某个权限;
-
Session Manager:会话管理,即用户登录后就是一次会话,在没有退出之前,它的所有信息都在会话中;会话可以是普通JavaSE环境的,也可以是如Web环境的;
-
Cryptography:加密,保护数据的安全性,如密码加密存储到数据库,而不是明文存储;
除以上功能外,shiro还提供了很多扩展如下
Web Support:Web支持,可以非常容易的集成到Web环境;
Caching:缓存,比如用户登录后,其用户信息、拥有的角色/权限不必每次去查,这样可以提高效率;
Concurrency:shiro支持多线程应用的并发验证,即如在一个线程中开启另一个线程,能把权限自动传播过去;
Testing:提供测试支持;
Run As:允许一个用户假装为另一个用户(如果他们允许)的身份进行访问;
Remember Me:记住我,这个是非常常见的功能,即一次登录后,下次再来的话不用登录了。
记住一点,Shiro不会去维护用户、维护权限;这些需要我们自己去设计/提供;然后通过相应的接口注入给Shiro即可。
主要架构阅览
Subject:主体,既可以代表用户,也可以代表程序(网络爬虫等),它需要访问系统,系统则需要对其进行认证和授权,可以看到主体可以是任何可以与应用交互的“用户”。
SecurityManager: 安全管理,用户请求Url,对应于一个Subject对象,由SecurityManager统一对Subject进行认证和授权(父)。
Authenricator: 认证器,主要对Subject进行认证,Subject的信息在shrio中是通过AuthenticationToken对象来储存,由AuthenricationStrategy进行验证管理.(子)。如果用户觉得Shiro默认的不好,可以自定义实现;其需要认证策略(Authentication Strategy),即什么情况下算用户认证通过了;
Authorizer:授权器,Subject认证后,由它来对其授予对应角色权限.(子)即控制着用户能访问应用中的哪些功能;
SessionManager: Shiro的session管理方式,Shiro提供了一个专门管理session的方式,通常的web程序中的session是HttpSession的对象,是由web容器来管理的.如果写过Servlet就应该知道Session的概念,Session呢需要有人去管理它的生命周期,这个组件就是SessionManager;而Shiro并不仅仅可以用在Web环境,也可以用在如普通的JavaSE环境、EJB等环境;所有呢,Shiro就抽象了一个自己的Session来管理主体与应用之间交互的数据;这样的话,比如我们在Web环境用,刚开始是一台Web服务器;接着又上了台EJB服务器;这时想把两台服务器的会话数据放到一个地方,这个时候就可以实现自己的分布式会话(如把数据放到Memcached服务器);
SessionDao: session的接口,Shiro通过它来管理session数据,个性化的session数据储存需要使用sessionDao.
CacheManager: 缓存控制器,主要对session数据和授权数据进行缓存,减小数据库的访问压力.可以通过和ehcache的整合对缓存数据进行管理.
Pluggable Realms: 可扩展领域,相当于数据源,我们通过上面内容可以大致了解到Shiro的工作原理,但Shiro是怎样得知Subject的信息和数据库的信息是否匹配呢?Shiro这里就提供了一个realms的概念,它的作用就是得到数据库中的信息.这个realm是可以多个并且可以自定义,只需继承AuthorizingRealm这个接口就可以了.可以有1个或多个Realm,可以认为是安全实体数据源,即用于获取安全实体的;可以是JDBC实现,也可以是LDAP实现,或者内存实现等等,由用户提供,Shiro不知道你的用户/权限存储在哪及以何种格式存储,所以我们一般在应用中都需要实现自己的Realm密码模块
注意:对Subject进行认证和授权都需要调用realm,所以realm不仅仅相当于数据源,更加包含了认证和授权的一种逻辑.
Cryptography: 密码模块,一个密码管理工具,提供了一套加密/解密的组件.比如常用的散列,加/解密等功能,日常练习所使用的md5算法其实是一种散列算法,只能加密,不能解密
可见Shrio的核心部分还是认证和授权部分,其他都是围绕这俩部分进行的,只需理解了这两部分就可以进行开发了.
Shiro认证流程
Shiro处理一个Subject流程图
subject用户
securityManager管理所有用户
ReaLm连接数据
可以看到:应用代码直接交互的对象是Subject,也就是说Shiro的对外API核心就是Subject;其每个API的含义:
Subject:主体,代表了当前“用户”,这个用户不一定是一个具体的人,与当前应用交互的任何东西都是Subject,如网络爬虫,机器人等;即一个抽象概念;所有Subject都绑定到SecurityManager,与Subject的所有交互都会委托给SecurityManager;可以把Subject认为是一个门面;SecurityManager才是实际的执行者; SecurityManager:安全管理器;即所有与安全有关的操作都会与SecurityManager交互;且它管理着所有Subject;可以看出它是Shiro的核心,它负责与后边介绍的其他组件进行交互,如果学习过SpringMVC,你可以把它看成DispatcherServlet前端控制器;
Realm:域,Shiro从Realm获取安全数据(如用户、角色、权限),就是说SecurityManager要验证用户身份,那么它需要从Realm获取相应的用户进行比较以确定用户身份是否合法;也需要从Realm得到用户相应的角色/权限进行验证用户是否能进行操作;可以把Realm看成DataSource,即安全数据源。也就是说对于我们而言,最简单的一个Shiro应用:
1、应用代码通过Subject来进行认证和授权,而Subject又委托给SecurityManager;
2、我们需要给Shiro的SecurityManager注入Realm,从而让SecurityManager能得到合法的用户及其权限进行判断。
从以上也可以看出,Shiro不提供维护用户/权限,而是通过Realm让开发人员自己注入。
Shiro处理认证流程图,相当于上图的扩充和细化
可见,Shiro处理流程是一级一级的调用,主要是调用Authentication来进行验证,最后还是需要使用realm来进行身份验证。
Shiro实践
查看官网文档:https://shiro.apache.org/tutorial.html
官方的quickstart:https://github.com/apache/shiro/tree/main/samples/quickstart
-
创建一个maven父工程,用于学习Shiro,删掉不必要的东西
-
根据官方文档,我们来导入Shiro的依赖
-
根据官方文档,我们来导入Shiro的依赖
pom导入依赖
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.14</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.4.1</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.21</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.7.21</version>
</dependency>
或者
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.4.1</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.21</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.7.21</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
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
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
Quickstart
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();
// 通过当前用户拿的Session
Session session = currentUser.getSession();
session.setAttribute("someKey", "aValue");
String value = (String) session.getAttribute("someKey");
if (value.equals("aValue")) {
log.info("Subject===> session[" + value + "]");
}
// currentUser.isAuthenticated()判断当前的用户是被认证
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);//结束系统
}
}
Shiro进行认证,拦截,整合mybatis,授权
pom
<!--shiro-Thymeleaf整合-->
<dependency>
<groupId>com.github.theborakompanioni</groupId>
<artifactId>thymeleaf-extras-shiro</artifactId>
<version>2.0.0</version>
</dependency>
<!--导入lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.22</version>
</dependency>
<!--导入mybatis整合包-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<!--导入shiro整合包-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.7.1</version>
</dependency>
<!--导入mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.27</version>
</dependency>
<!--导入Druid数据园-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.7</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!-- 引入thymeleaf的依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!--引入web依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--Spring Boot启动器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
ShiroConfig
package com.yuan.config;
import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
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 {
//第三步ecurityManager
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("ecurityManager") DefaultWebSecurityManager defaultWebSecurityManager) {
ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
bean.setSecurityManager(defaultWebSecurityManager);
//添加shiro的内置过滤器
/**
* anon:无需认证就可以访问
* authc:必须认证了才能让问
* user:必须拥有记住我功能才能用
* perms :拥有对某个资源的权限才能访问;
* roLe:拥有某个角色权限才能访问
*/
//设置访问权限 拦截
//设置控制map
Map<String,String> filterMap = new LinkedHashMap<>();
//授权 正常的情况下,会跳转到未授权页面
//put("controller的跳转页面一一对应","权限:从数据库查询")
filterMap.put("/user/add","perms[user:add]"); //是user并且要有add的权限才能访问
filterMap.put("/user/update","perms[user:update]"); //是user并且要有update的权限才能访问
filterMap.put("/user/*","authc");//user下面的页面必须认证才能访问 代表user下面的所有页面需要认证
filterMap.put("/logout","logout");//实现登出功能 MyController下的 @RequestMapping("/logout")
bean.setFilterChainDefinitionMap(filterMap);
//没有权限跳转到登录页面
bean.setLoginUrl("/toLogin");
//跳转到未授权页面
bean.setUnauthorizedUrl("/noauto");
return bean;
}
//DefaultWebSecurityManager第二步
@Bean(name = "ecurityManager")
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();
}
//整合ShiroDialect:用来整合 shiro thymeleaf
@Bean
public ShiroDialect shiroDialect() {
return new ShiroDialect();
}
}
UserRealmConfig
package com.yuan.config;
import com.yuan.pojo.User;
import com.yuan.service.UserService;
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;
//自定义的UserRealm
public class UserRealm extends AuthorizingRealm {
@Autowired
private UserService userService;
//授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("执行了===>授权doGetAuthorizationInfo");
//SimpleAuthorizationInfo
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
// info.addStringPermission("user:add");//给所有用户授予user:add权限
//拿到当前登录的对象
Subject subject = SecurityUtils.getSubject();
User currentUser = (User) subject.getPrincipal();//获取传递的值user值 拿到user对象 SimpleAuthenticationInfo(user,"","")
//设置当前用户的权限
info.addStringPermission(currentUser.getPerms());
return info;
}
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToke) throws AuthenticationException {
System.out.println("执行了===>认证doGetAuthorizationInfo");
//用户名,密码
UsernamePasswordToken userToken=(UsernamePasswordToken) authenticationToke;
User user = userService.userByName(userToken.getUsername());
if (user == null) {//没有这个人
return null;//抛出异常 UnknownAccountException 用户名有误
}
//获取session
Subject subject = SecurityUtils.getSubject();
Session session = subject.getSession();
session.setAttribute("LoginUser",user);//存放session
//可以加密: MD5:ei0adc3949ba59abbe56e057f20f883e MD5盐值加密:e10adc3949ba59abbe56e657f20f883e 跟一个用户名username
//密码认证 加密
return new SimpleAuthenticationInfo(user,user.getPassword(),"");
//SimpleAuthenticationInfo(吧值传递个授权,判断密码是否正确与数据库相符,"")
}
}
MyController
package com.yuan.controller;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* 控制层
*/
@Controller
public class MyController {
/**
* 跳转到主要面
* @param model
* @return
*/
@RequestMapping({"/","toIndex"})
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";
}
@RequestMapping("/toLogin")
public String toLogin() {
return "/login";
}
/**
* 登录用户认证
* @param username
* @param password
* @param model
* @return
*/
@RequestMapping("/login")
public String login(String username,String password,Model model) {
//获取当前用户的Subject
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";
}
}
/**
* 如果没有权限显示
* @return
*/
@RequestMapping("/noauto")
@ResponseBody
public String unauthorized(){
return "未经授权的页面禁止访问";
}
/**
* 注销
*/
@RequestMapping("/logout")
public String logout(Session session,Model model){
Subject subject = SecurityUtils.getSubject();
subject.logout();
model.addAttribute("msg", "安全退出");
return "/login";
}
}
UserMapper
package com.yuan.mapper;
import com.yuan.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
/**
* mapper层
*/
@Repository
@Mapper
public interface UserMapper {
/**
* 查询一个用户
* @param username
* @return
*/
public User userByName(@Param("username") String username);
}
User
package com.yuan.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@AllArgsConstructor
@NoArgsConstructor
@Data
public class User {
private int id;//编号
private String username;//用户名
private String password;//密码
private String perms;//权限 user:add,user:update
}
UserService
/**
* 业务接口
*/
public interface UserService {
/**
* 查询一个用户
* @param username
* @return
*/
public User userByName(String username);
}
UserServiceImpl
package com.yuan.service.impl;
import com.yuan.mapper.UserMapper;
import com.yuan.pojo.User;
import com.yuan.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* 业务实现类
*/
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
/**
* 查询一个用户
* @param username
*/
@Override
public User userByName(String username) {
return userMapper.userByName(username);
}
}
UserMapper.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.yuan.mapper.UserMapper">
<!--查询一个用户-->
<select id="userByName" resultType="User" >
select * from `user` WHERE username=#{username}
</select>
</mapper>
application.yaml
spring:
datasource:
username: root
password: root
url: jdbc:mysql://localhost:3306/studentdb?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true
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
application.properties
#关闭thymeleaf 缓存
spring.thymeleaf.cache=false
##实体类
mybatis.type-aliases-package=com.yuan.pojo
#扫描资源报下的mapper
mybatis.mapper-locations=classpath:mapper/*.xml
login.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" >
<title>Title</title>
</head>
<body>
<p th:text="${msg}" style="color: red"></p>
<form th:action="@{/login}">
<p>用户名: <input type="text" name="username"/></p>
<p> 密码:<input type="password" name="password"/></p>
<p><input type="submit"></p>
</form>
</body>
</html>
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>Title</title>
</head>
<body>
<h1>首页</h1>
<p th:text="${msg}"></p>
<!--从session取值,如果session为空显示登录-->
<p th:if="${session.LoginUser==null}">
<a th:href="@{/toLogin}">登录</a>
</p>
<p th:if="${session.LoginUser!=null}">
<a th:href="@{/logout}">注销</a>
</p>
<!--如果有add权限显示aaa-->
<div shiro:haspermission="user:add">
<a href="/user/add">add</a>
</div>
<!--如果有update权限显示update-->
<div shiro:haspermission="user:update">
<a href="/user/update">update</a>
</div>
</body>
</html>
add.index
<!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>