Shiro整合Springboot之thymeleaf模板

引入依赖

<dependency>
   <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

<!--引入thymeleaf解析依赖-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

<dependency>
    <groupId>com.github.theborakompanioni</groupId>
    <artifactId>thymeleaf-extras-shiro</artifactId>
    <version>2.0.0</version>
</dependency>

<!--引入shiro整合springboot依赖-->
<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-spring-boot-starter</artifactId>
    <version>1.5.3</version>
</dependency>

<!--mybatis相关依赖-->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.4</version>
</dependency>

<!--mysql-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.39</version>
</dependency>

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.13</version>
</dependency>

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.4</version>
</dependency>

<!--引入shiro和ehcahce依赖-->
<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-ehcache</artifactId>
    <version>1.5.3</version>
</dependency>

<!--redis整合springboot-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

配置文件配置(application.properties)

server.port=8889
server.servlet.context-path=/shiro
spring.application.name=shiro

spring.thymeleaf.cache=false
spring.thymeleaf.suffix=.html
spring.mvc.view.prefix=classpath:/templates/

spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/shiro?characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=root

mybatis.type-aliases-package=com.mu.springbootshirothymeleaf.entity
mybatis.mapper-locations=classpath:mapper/*.xml

spring.redis.port=6379
spring.redis.host=localhost
spring.redis.database=0

logging.level.com.mu.springbootshirothymeleaf.dao=debug

shiro的配置类

/**
 * 用来整合shiro框架相关的配置类
 */
@Configuration
public class ShiroConfig {
    
    

    /**
     * 页面标签不起作用一定要记住加入方言处理
     * @return
     */
    @Bean(name = "shiroDialect")
    public ShiroDialect shiroDialect(){
    
    
        return new ShiroDialect();
    }

    //1.创建shiroFilter,负责拦截所有请求
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager){
    
    
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();

        //给filter设置安全管理器
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);

        //配置系统受限资源
        //配置系统公共资源
        Map<String,String> map = new HashMap<>();
        map.put("/login.html","anon");
        map.put("/user/getImage","anon");
        map.put("/user/register","anon");
        map.put("/user/registerview","anon");
        map.put("/user/login","anon");

        map.put("/**", "authc");  //authc 请求这个资源需要认证和授权

        //默认认证界面路径
        shiroFilterFactoryBean.setLoginUrl("/user/loginview");

        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);

        return shiroFilterFactoryBean;
    }

    //2.创建安全管理器
    @Bean
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("getRealm") Realm realm){
    
    
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();

        //给安全管理器设置
        defaultWebSecurityManager.setRealm(realm);


        return defaultWebSecurityManager;
    }

    //3.创建自定义Realm
    @Bean
    public Realm getRealm(){
    
    
        CustomerRealm customerRealm = new CustomerRealm();
        //修改凭证校验匹配器
        HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
        //设置加密算法为md5
        credentialsMatcher.setHashAlgorithmName("MD5");
        //设置散列次数
        credentialsMatcher.setHashIterations(1024);
        customerRealm.setCredentialsMatcher(credentialsMatcher);

        //开启shiro缓存管理
        /*customerRealm.setCacheManager(new EhCacheManager());
        customerRealm.setCachingEnabled(true);  //开启全局缓存
        customerRealm.setAuthenticationCachingEnabled(true);  //开启认证缓存
        customerRealm.setAuthenticationCacheName("authenticationCache");
        customerRealm.setAuthorizationCachingEnabled(true);  //开启授权缓存
        customerRealm.setAuthorizationCacheName("authorizationCache");*/

        //开启redis缓存管理
        customerRealm.setCacheManager(new RedisCacheManager());
        customerRealm.setCachingEnabled(true);  //开启全局缓存
        customerRealm.setAuthenticationCachingEnabled(true);  //开启认证缓存
        customerRealm.setAuthenticationCacheName("authenticationCache");
        customerRealm.setAuthorizationCachingEnabled(true);  //开启授权缓存
        customerRealm.setAuthorizationCacheName("authorizationCache");

        return customerRealm;
    }

}

创建自定义Realm

/**
 * 自定义Realm
 */
public class CustomerRealm extends AuthorizingRealm {
    
    

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
    
    
        System.out.println("用户授权。。。");
        //获取身份信息
        String primaryPrincipal = (String) principalCollection.getPrimaryPrincipal();

        //根据主身份信息获取角色 和 权限信息
        /*if("zhangsan".equals(primaryPrincipal)){
            SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();

            simpleAuthorizationInfo.addRole("admin");
            simpleAuthorizationInfo.addStringPermission("user:find:*");
            simpleAuthorizationInfo.addStringPermission("user:update:*");

            return simpleAuthorizationInfo;
        }*/
        UserService userService = (UserService) ApplicationContextUtils.getBean("userService");
        User user = userService.findRolesByUserName(primaryPrincipal);
        //授权角色信息
        if(!CollectionUtils.isEmpty(user.getRoles())){
    
    
            SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
            user.getRoles().forEach(role -> {
    
    
                simpleAuthorizationInfo.addRole(role.getName());

                //权限信息
                List<Permission> permissions = userService.findPermissionByRoleId(role.getId());
                if(!CollectionUtils.isEmpty(permissions)){
    
    
                    permissions.forEach(permission -> {
    
    
                        simpleAuthorizationInfo.addStringPermission(permission.getName());
                    });
                }
            });
            return  simpleAuthorizationInfo;
        }

        return null;
    }

    /**
     * 认证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    
    
        System.out.println("=====");
        String principal = (String) token.getPrincipal();
        //SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(principal, "123", this.getName());
        /*if("zhangsan".equals(principal)){
            return simpleAuthenticationInfo;
        }*/
        //在工厂中获取service对象
        /*UserService userService = (UserService) ApplicationContextUtils.getBean("userService");
        User user = userService.findByUserName(principal);
        if(!ObjectUtils.isEmpty(user)){
            return new SimpleAuthenticationInfo(user.getUsername(),user.getPassword(),
                    ByteSource.Util.bytes(user.getSalt()),this.getName());
        }*/

        /**
         * redis缓存使用后,自定义salt实现 实现序列化接口
         */
        UserService userService = (UserService) ApplicationContextUtils.getBean("userService");
        User user = userService.findByUserName(principal);
        if(!ObjectUtils.isEmpty(user)){
    
    
            return new SimpleAuthenticationInfo(user.getUsername(),user.getPassword(),
                    new MyByteSource(user.getSalt()),this.getName());
        }

        return null;

    }
}

创建数据库表结构

/*
Navicat MySQL Data Transfer

Source Server         : localhost
Source Server Version : 50551
Source Host           : localhost:3306
Source Database       : shiro

Target Server Type    : MYSQL
Target Server Version : 50551
File Encoding         : 65001

Date: 2021-09-20 05:05:02
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for permission
-- ----------------------------
DROP TABLE IF EXISTS `permission`;
CREATE TABLE `permission` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `url` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Table structure for role
-- ----------------------------
DROP TABLE IF EXISTS `role`;
CREATE TABLE `role` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Table structure for role_permission
-- ----------------------------
DROP TABLE IF EXISTS `role_permission`;
CREATE TABLE `role_permission` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `role_id` int(11) DEFAULT NULL,
  `permission_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) DEFAULT NULL,
  `password` varchar(255) DEFAULT NULL,
  `salt` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Table structure for user_role
-- ----------------------------
DROP TABLE IF EXISTS `user_role`;
CREATE TABLE `user_role` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) DEFAULT NULL,
  `role_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

开发注册界面

<!doctype html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <h1>用户注册</h1>

    <form th:action="@{/user/register}" method="post">
        用户名:<input type="text" name="username"><br/>
        密码: <input type="text" name="password"><br/>
        <input type="submit" value="注册">
    </form>

</body>
</html>

开发登录界面

<!doctype html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <h1>用户登录</h1>

    <form th:action="@{/user/login}" method="post">
        用户名:<input type="text" name="username"><br/>
        密码: <input type="text" name="password"><br/>
        请输入验证码:<input type="text" name="code"><img th:src="@{/user/getImage}" alt=""><br/>
        <input type="submit" value="登录">
    </form>
    <a th:href="@{/user/registerview}"></a>

</body>
</html>

开发列表界面

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <meta charset="UTF-8">
    <title>index.html</title>
</head>
<body>
    <h1>欢迎访问主页</h1>

    <!--获取身份信息-->
    <span shiro:principal=""></span>

    <!--认证处理-->
    <span shiro:notAuthenticated="">
        认证通过展示内容
    </span>
    <span shiro:notAuthenticated="">
        没有认证展示的内容
    </span>
    <!--授权角色-->
    <span shiro:hasRole="admin">
        this is admin
    </span>
    <!---->
</body>
</html>

创建entity

1.用户实体

@Data
@Accessors(chain = true)
@AllArgsConstructor
@NoArgsConstructor
public class User {
    
    
    private Integer id;
    private String username;
    private String password;
    private String salt;

    //定义角色集合
    private List<Role> roles;

}

2.角色实体

@Data
@Accessors(chain = true)
@AllArgsConstructor
@NoArgsConstructor
public class Role {
    
    

    private Integer id;
    private String name;

    //定义权限的集合
    private List<Permission> permissions;

}

3.权限实体

@Data
@Accessors(chain = true)
@AllArgsConstructor
@NoArgsConstructor
public class Permission {
    
    

    private Integer id;
    private String name;
    private String url;

}

创建Dao接口

@Mapper
public interface UserDao {
    
    

    void save(User user);

    User findByUserName(String username);

    //根据用户名查询所有角色
    User findRolesByUserName(String uesrname);

    //根据角色id查询权限集合
    List<Permission> findPermissionByRoleId(Integer id);

}

开发mapper配置文件

<?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.mu.springbootshirothymeleaf.dao.UserDao">
    <insert id="save" parameterType="com.mu.springbootshirothymeleaf.entity.User" useGeneratedKeys="true" keyProperty="id">
        insert into user values(#{
    
    id},#{
    
    username},#{
    
    password},#{
    
    salt})
    </insert>

    <select id="findByUserName" parameterType="String" resultType="com.mu.springbootshirothymeleaf.entity.User">
        select * from user where username =#{
    
    username}
    </select>

    <resultMap id="userMap" type="com.mu.springbootshirothymeleaf.entity.User">
        <id column="uid" property="id"/>
        <result column="username" property="username"/>
        <!--角色信息-->
        <collection property="roles" javaType="list" ofType="com.mu.springbootshirothymeleaf.entity.Role">
            <id column="rid" property="id"/>
            <result column="rname" property="name"/>
        </collection>
    </resultMap>

    <select id="findRolesByUserName" resultType="String" resultMap="userMap">
        SELECT
            u.id uid,
            u.username username,
            r.id rid,
            r.`name` rname
        FROM
            `user` u
        LEFT JOIN user_role ur ON u.id = ur.user_id
        LEFT JOIN role r ON ur.role_id = r.id
        WHERE
            u.username =#{
    
    username}
    </select>

    <select id="findPermissionByRoleId" parameterType="Integer" resultType="com.mu.springbootshirothymeleaf.entity.Permission">
        SELECT
            p.id,
            p.`name`,
            p.url,
            r.`name`
        FROM
            role r
        LEFT JOIN role_permission rp ON r.id = rp.role_id
        LEFT JOIN permission p ON rp.permission_id = p.id
        WHERE r.id =#{
    
    roleId}
    </select>

</mapper>

开发service接口

public interface UserService {
    
    
    void save(User user);

    User findByUserName(String username);

    //根据用户名查询所有角色
    User findRolesByUserName(String uesrname);

    //根据角色id查询权限集合
    List<Permission> findPermissionByRoleId(Integer id);

}

创建salt工具栏

public class SaltUtils {
    
    

    public static String getSalt(int n){
    
    

        char[] chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()".toCharArray();
        StringBuilder sb = new StringBuilder();
        for (int i=0;i<n;i++){
    
    
            char aChar = chars[new Random().nextInt(chars.length)];
            sb.append(aChar);
        }
        return sb.toString();

    }

}

创建ApplicationContextUtils工具类

@Component
public class ApplicationContextUtils implements ApplicationContextAware {
    
    

    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    
    
        this.context = applicationContext;
    }

    //根据bean名字获取工厂中指定bean对象
    public static Object getBean(String beanName){
    
    
        return context.getBean(beanName);
    }

}

开发service实现类

@Service("userService")
@Transactional
public class UserServiceImpl implements UserService {
    
    

    @Autowired
    private UserDao userDao;

    @Override
    public void save(User user) {
    
    
        //处理业务调用dao
        //1.生成随机盐
        String salt = SaltUtils.getSalt(8);
        //2.将随机盐保存到数据库
        user.setSalt(salt);
        //3.明文密码进行md5 + salt + hash散列
        Md5Hash md5Hash = new Md5Hash(user.getPassword(),salt, 1024);
        user.setPassword(md5Hash.toHex());
        userDao.save(user);
    }

    @Override
    public User findByUserName(String username) {
    
    
        return userDao.findByUserName(username);
    }

    @Override
    public User findRolesByUserName(String uesrname) {
    
    
        return userDao.findRolesByUserName(uesrname);
    }

    @Override
    public List<Permission> findPermissionByRoleId(Integer id) {
    
    
        return userDao.findPermissionByRoleId(id);
    }
}

开发Controller

1.UserController

@Controller
@RequestMapping("user")
public class UserController {
    
    

    @Autowired
    private UserService userService;

    /**
     * 跳转到register请求
     */
    @RequestMapping("registerview")
    public String register(){
    
    
        System.out.println("跳转到register的html");
        return "register";
    }

    /**
     * 跳转到login请求
     */
    @RequestMapping("loginview")
    public String login(){
    
    
        System.out.println("跳转到login的html");
        return "login";
    }

    /**
     * 验证码方法
     */
    @RequestMapping("getImage")
    public void getImage(HttpSession session, HttpServletResponse response) throws IOException {
    
    
        //生成验证码
        String code = VerifyCodeUtils.generateVerifyCode(4);
        //验证码放入session
        session.setAttribute("code",code);
        //验证码存入图片
        ServletOutputStream os = response.getOutputStream();
        response.setContentType("image/png");
        VerifyCodeUtils.outputImage(220,60,os,code);
    }

    @RequestMapping("/login")
    public String login(String username, String password,String code,HttpSession session){
    
    
        //比较验证码
        String codes = (String) session.getAttribute("code");
        if(codes.equalsIgnoreCase(code)){
    
    
            //获取主体对象
            Subject subject = SecurityUtils.getSubject();
            try{
    
    
                subject.login(new UsernamePasswordToken(username, password));
                return "redirect:/index";
            }catch (UnknownAccountException e){
    
    
                e.printStackTrace();
                System.out.println("用户名错误!");
            }catch (IncorrectCredentialsException e){
    
    
                e.printStackTrace();
                System.out.println("密码错误!");
            }
        }else{
    
    
            throw new RuntimeException("验证码错误!");
        }
        return "redirect:/user/loginview";
    }

    /**
     * 退出登录
     * @return
     */
    @RequestMapping("/logout")
    public String logout(){
    
    
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:/user/loginview";
    }

    /**
     * 用户登录
     * @param user
     * @return
     */
    @RequestMapping("/register")
    public String register(User user){
    
    
        try {
    
    
            userService.save(user);
            return "redirect:/user/loginview";
        }catch (Exception e){
    
    
            e.printStackTrace();
            return "redirect:/user/registerview";
        }
    }
}

2.IndexController

@Controller
public class IndexController {
    
    
    @RequestMapping("index")
    public String hello(){
    
    
        System.out.println("index主页 springboot shiro thymeleaf");
        return "index";
    }
}

自定义salt实现 实现序列化接口

/**
 * 自定义salt实现 实现序列化接口
 */
public class MyByteSource implements ByteSource,Serializable {
    
    

    private  byte[] bytes;
    private String cachedHex;
    private String cachedBase64;

    public MyByteSource(){
    
    

    }

    public MyByteSource(byte[] bytes) {
    
    
        this.bytes = bytes;
    }

    public MyByteSource(char[] chars) {
    
    
        this.bytes = CodecSupport.toBytes(chars);
    }

    public MyByteSource(String string) {
    
    
        this.bytes = CodecSupport.toBytes(string);
    }

    public MyByteSource(ByteSource source) {
    
    
        this.bytes = source.getBytes();
    }

    public MyByteSource(File file) {
    
    
        this.bytes = (new MyByteSource.BytesHelper()).getBytes(file);
    }

    public MyByteSource(InputStream stream) {
    
    
        this.bytes = (new MyByteSource.BytesHelper()).getBytes(stream);
    }

    public static boolean isCompatible(Object o) {
    
    
        return o instanceof byte[] || o instanceof char[] || o instanceof String || o instanceof ByteSource || o instanceof File || o instanceof InputStream;
    }

    public byte[] getBytes() {
    
    
        return this.bytes;
    }

    public boolean isEmpty() {
    
    
        return this.bytes == null || this.bytes.length == 0;
    }

    public String toHex() {
    
    
        if (this.cachedHex == null) {
    
    
            this.cachedHex = Hex.encodeToString(this.getBytes());
        }

        return this.cachedHex;
    }

    public String toBase64() {
    
    
        if (this.cachedBase64 == null) {
    
    
            this.cachedBase64 = Base64.encodeToString(this.getBytes());
        }

        return this.cachedBase64;
    }

    public String toString() {
    
    
        return this.toBase64();
    }

    public int hashCode() {
    
    
        return this.bytes != null && this.bytes.length != 0 ? Arrays.hashCode(this.bytes) : 0;
    }

    public boolean equals(Object o) {
    
    
        if (o == this) {
    
    
            return true;
        } else if (o instanceof ByteSource) {
    
    
            ByteSource bs = (ByteSource)o;
            return Arrays.equals(this.getBytes(), bs.getBytes());
        } else {
    
    
            return false;
        }
    }

    private static final class BytesHelper extends CodecSupport {
    
    
        private BytesHelper() {
    
    
        }

        public byte[] getBytes(File file) {
    
    
            return this.toBytes(file);
        }

        public byte[] getBytes(InputStream stream) {
    
    
            return this.toBytes(stream);
        }
    }

}

验证码生成类

/**
 * 验证码生成
 */
public class VerifyCodeUtils {
    
    

    //使用到Algerian字体,系统里没有的话需要安装字体,字体只显示大写,去掉了1,0,i,o几个容易混淆的字符
    public static final String VERIFY_CODES = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
    private static Random random = new Random();


    /**
     * 使用系统默认字符源生成验证码
     * @param verifySize    验证码长度
     * @return
     */
    public static String generateVerifyCode(int verifySize){
    
    
        return generateVerifyCode(verifySize, VERIFY_CODES);
    }

    /**
     * 使用指定源生成验证码
     * @param verifySize    验证码长度
     * @param sources   验证码字符源
     * @return
     */
    public static String generateVerifyCode(int verifySize, String sources){
    
    
        if(sources == null || sources.length() == 0){
    
    
            sources = VERIFY_CODES;
        }
        int codesLen = sources.length();
        Random rand = new Random(System.currentTimeMillis());
        StringBuilder verifyCode = new StringBuilder(verifySize);
        for(int i = 0; i < verifySize; i++){
    
    
            verifyCode.append(sources.charAt(rand.nextInt(codesLen-1)));
        }
        return verifyCode.toString();
    }

    /**
     * 生成随机验证码文件,并返回验证码值
     * @param w
     * @param h
     * @param outputFile
     * @param verifySize
     * @return
     * @throws IOException
     */
    public static String outputVerifyImage(int w, int h, File outputFile, int verifySize) throws IOException {
    
    
        String verifyCode = generateVerifyCode(verifySize);
        outputImage(w, h, outputFile, verifyCode);
        return verifyCode;
    }

    /**
     * 输出随机验证码图片流,并返回验证码值
     * @param w
     * @param h
     * @param os
     * @param verifySize
     * @return
     * @throws IOException
     */
    public static String outputVerifyImage(int w, int h, OutputStream os, int verifySize) throws IOException{
    
    
        String verifyCode = generateVerifyCode(verifySize);
        outputImage(w, h, os, verifyCode);
        return verifyCode;
    }

    /**
     * 生成指定验证码图像文件
     * @param w
     * @param h
     * @param outputFile
     * @param code
     * @throws IOException
     */
    public static void outputImage(int w, int h, File outputFile, String code) throws IOException{
    
    
        if(outputFile == null){
    
    
            return;
        }
        File dir = outputFile.getParentFile();
        if(!dir.exists()){
    
    
            dir.mkdirs();
        }
        try{
    
    
            outputFile.createNewFile();
            FileOutputStream fos = new FileOutputStream(outputFile);
            outputImage(w, h, fos, code);
            fos.close();
        } catch(IOException e){
    
    
            throw e;
        }
    }

    /**
     * 输出指定验证码图片流
     * @param w
     * @param h
     * @param os
     * @param code
     * @throws IOException
     */
    public static void outputImage(int w, int h, OutputStream os, String code) throws IOException{
    
    
        int verifySize = code.length();
        BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        Random rand = new Random();
        Graphics2D g2 = image.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
        Color[] colors = new Color[5];
        Color[] colorSpaces = new Color[] {
    
     Color.WHITE, Color.CYAN,
                Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE,
                Color.PINK, Color.YELLOW };
        float[] fractions = new float[colors.length];
        for(int i = 0; i < colors.length; i++){
    
    
            colors[i] = colorSpaces[rand.nextInt(colorSpaces.length)];
            fractions[i] = rand.nextFloat();
        }
        Arrays.sort(fractions);

        g2.setColor(Color.GRAY);// 设置边框色
        g2.fillRect(0, 0, w, h);

        Color c = getRandColor(200, 250);
        g2.setColor(c);// 设置背景色
        g2.fillRect(0, 2, w, h-4);

        //绘制干扰线
        Random random = new Random();
        g2.setColor(getRandColor(160, 200));// 设置线条的颜色
        for (int i = 0; i < 20; i++) {
    
    
            int x = random.nextInt(w - 1);
            int y = random.nextInt(h - 1);
            int xl = random.nextInt(6) + 1;
            int yl = random.nextInt(12) + 1;
            g2.drawLine(x, y, x + xl + 40, y + yl + 20);
        }

        // 添加噪点
        float yawpRate = 0.05f;// 噪声率
        int area = (int) (yawpRate * w * h);
        for (int i = 0; i < area; i++) {
    
    
            int x = random.nextInt(w);
            int y = random.nextInt(h);
            int rgb = getRandomIntColor();
            image.setRGB(x, y, rgb);
        }

        shear(g2, w, h, c);// 使图片扭曲

        g2.setColor(getRandColor(100, 160));
        int fontSize = h-4;
        Font font = new Font("Algerian", Font.ITALIC, fontSize);
        g2.setFont(font);
        char[] chars = code.toCharArray();
        for(int i = 0; i < verifySize; i++){
    
    
            AffineTransform affine = new AffineTransform();
            affine.setToRotation(Math.PI / 4 * rand.nextDouble() * (rand.nextBoolean() ? 1 : -1), (w / verifySize) * i + fontSize/2, h/2);
            g2.setTransform(affine);
            g2.drawChars(chars, i, 1, ((w-10) / verifySize) * i + 5, h/2 + fontSize/2 - 10);
        }

        g2.dispose();
        ImageIO.write(image, "jpg", os);
    }

    private static Color getRandColor(int fc, int bc) {
    
    
        if (fc > 255)
            fc = 255;
        if (bc > 255)
            bc = 255;
        int r = fc + random.nextInt(bc - fc);
        int g = fc + random.nextInt(bc - fc);
        int b = fc + random.nextInt(bc - fc);
        return new Color(r, g, b);
    }

    private static int getRandomIntColor() {
    
    
        int[] rgb = getRandomRgb();
        int color = 0;
        for (int c : rgb) {
    
    
            color = color << 8;
            color = color | c;
        }
        return color;
    }

    private static int[] getRandomRgb() {
    
    
        int[] rgb = new int[3];
        for (int i = 0; i < 3; i++) {
    
    
            rgb[i] = random.nextInt(255);
        }
        return rgb;
    }

    private static void shear(Graphics g, int w1, int h1, Color color) {
    
    
        shearX(g, w1, h1, color);
        shearY(g, w1, h1, color);
    }

    private static void shearX(Graphics g, int w1, int h1, Color color) {
    
    

        int period = random.nextInt(2);

        boolean borderGap = true;
        int frames = 1;
        int phase = random.nextInt(2);

        for (int i = 0; i < h1; i++) {
    
    
            double d = (double) (period >> 1)
                    * Math.sin((double) i / (double) period
                    + (6.2831853071795862D * (double) phase)
                    / (double) frames);
            g.copyArea(0, i, w1, 1, (int) d, 0);
            if (borderGap) {
    
    
                g.setColor(color);
                g.drawLine((int) d, i, 0, i);
                g.drawLine((int) d + w1, i, w1, i);
            }
        }

    }

    private static void shearY(Graphics g, int w1, int h1, Color color) {
    
    

        int period = random.nextInt(40) + 10; // 50;

        boolean borderGap = true;
        int frames = 20;
        int phase = 7;
        for (int i = 0; i < w1; i++) {
    
    
            double d = (double) (period >> 1)
                    * Math.sin((double) i / (double) period
                    + (6.2831853071795862D * (double) phase)
                    / (double) frames);
            g.copyArea(i, 0, 1, h1, 0, (int) d);
            if (borderGap) {
    
    
                g.setColor(color);
                g.drawLine(i, (int) d, i, 0);
                g.drawLine(i, (int) d + h1, i, h1);
            }

        }

    }

}

自定义redis缓存的实现

/**
 * 自定义redis缓存的实现
 */
public class RedisCache<k,v> implements Cache<k,v> {
    
    

    private String cacheName;

    public RedisCache() {
    
    

    }

    public RedisCache(String cacheName) {
    
    
        this.cacheName = cacheName;
    }

    @Override
    public v get(k k) throws CacheException {
    
    
        System.out.println("put key:" + k);
        //return (v) getRedisTemplate().opsForValue().get(k.toString());
        return (v) getRedisTemplate().opsForHash().get(this.cacheName, k.toString());
    }

    @Override
    public v put(k k, v v) throws CacheException {
    
    
        System.out.println("put key:" + k);
        System.out.println("put value:" + v);
        //getRedisTemplate().opsForValue().set(k.toString(),v);
        getRedisTemplate().opsForHash().put(this.cacheName, k.toString(), v);
        return null;
    }

    @Override
    public v remove(k k) throws CacheException {
    
    
        return (v)getRedisTemplate().opsForHash().delete(this.cacheName, k.toString());
    }

    @Override
    public void clear() throws CacheException {
    
    
        getRedisTemplate().delete(this.cacheName);
    }

    @Override
    public int size() {
    
    
        return getRedisTemplate().opsForHash().size(this.cacheName).intValue();
    }

    @Override
    public Set<k> keys() {
    
    
        return getRedisTemplate().opsForHash().keys(this.cacheName);
    }

    @Override
    public Collection<v> values() {
    
    
        return getRedisTemplate().opsForHash().values(this.cacheName);
    }

    public RedisTemplate getRedisTemplate(){
    
    
        RedisTemplate redisTemplate = (RedisTemplate) ApplicationContextUtils.getBean("redisTemplate");
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        return redisTemplate;
    }
}

自定义shiro缓存管理器

/**
 * 自定义shiro缓存管理器
 */
public class RedisCacheManager implements CacheManager {
    
    

    /**
     *
     * @param cacheName  认证或者授权缓存的统一名称
     * @param <K>
     * @param <V>
     * @return
     * @throws CacheException
     */
    @Override
    public <K, V> Cache<K, V> getCache(String cacheName) throws CacheException {
    
    
        System.out.println(cacheName);
        return new RedisCache<>(cacheName);
    }
}

猜你喜欢

转载自blog.csdn.net/muriyue6/article/details/120397130
今日推荐