java生成在线验证码

该博客介绍了如何在Java中使用Maven依赖生成验证码,包括静态和动态验证码的创建,并展示了结合Redis进行验证码存储与验证的方法。同时,文章讲解了如何通过SpringContextUtil获取应用的运行环境,以及获取本地和公网IP地址的实现。
摘要由CSDN通过智能技术生成

1、生成验证码

1、maven包

​
       <dependency>
            <groupId>com.github.whvcse</groupId>
            <artifactId>easy-captcha</artifactId>
            <version>1.6.2</version>
        </dependency>

​

2、接口测试一

    @GetMapping("/captcha")
    public Result captcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
  CaptchaUtil.out(request, response);
}

3、接口测试二

    @GetMapping("/captcha")
    public Result captcha(HttpServletRequest request, HttpServletResponse response) throws Exception {

        //第二种
//        // 设置位数
  CaptchaUtil.out(5, request, response);
//        // 设置宽、高、位数
 CaptchaUtil.out(130, 48, 5, request, response);
//
//        // 使用gif验证码
GifCaptcha gifCaptcha = new GifCaptcha(130,48,4);
CaptchaUtil.out(gifCaptcha, request, response);
}

3、接口测试三(结合redis)

  @GetMapping("/captcha")
    public Result captcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 5);
        String verCode = specCaptcha.text().toLowerCase();
        String key = UUID.randomUUID().toString();
        redisUtil.opsForValue().set(key, verCode, 30, TimeUnit.MINUTES);
        // 将key和base64返回给前端
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("key", key);
        hashMap.put("image", specCaptcha.toBase64());
        return Result.ok(hashMap);
    }
   @Override
    public Result makeCode() {
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 5);
        specCaptcha.setCharType(Captcha.TYPE_ONLY_LOWER);
        String verCode = specCaptcha.text().toUpperCase();
        String key = UUID.randomUUID().toString();
//        System.out.println(key);
//        System.out.println(verCode);
        redisUtil.opsForValue().set(key, verCode, 60*10, TimeUnit.SECONDS);
        // 将key和base64返回给前端
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("codeKey", key);
        hashMap.put("imageCode", specCaptcha.toBase64());
        return Result.ok(hashMap);
    }

验证码数据统一转化为大写 

   String verCode = specCaptcha.text().toUpperCase();
  @Override
    public void makeCodeTwo(String uuid, HttpServletResponse response) throws IOException {

        if(StringUtils.isBlank(uuid)){
            response.setContentType("application/json;charset=UTF-8");
            //设置编码格式
            response.setCharacterEncoding("UTF-8");
            response.setStatus(401);
            response.getWriter().write("uuid不能为空");
        }
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 5);
        specCaptcha.setCharType(Captcha.TYPE_ONLY_LOWER);
        String verCode = specCaptcha.text().toUpperCase();
        redisUtil.opsForValue().set(uuid, verCode, 60*10, TimeUnit.SECONDS);
        specCaptcha.out(response.getOutputStream());
    }

2、java加载配置信息判断(dev或者pro)

一、配置信息注入容器

@Component
public class SpringContextUtil implements ApplicationContextAware {
 
    private static ApplicationContext context = null;
 

    @Override
    public void setApplicationContext(ApplicationContext applicationContext)
            throws BeansException {
        this.context = applicationContext;
    }
 
    // 传入线程中
    public static <T> T getBean(String beanName) {
        return (T) context.getBean(beanName);
    }
 
    // 国际化使用
    public static String getMessage(String key) {
        return context.getMessage(key, null, Locale.getDefault());
    }
 
    /// 获取当前环境
    public static String getActiveProfile() {
        return context.getEnvironment().getActiveProfiles()[0];
    }
}

二、获取当前环境

String activeProfile = SpringContextUtil.getActiveProfile();

3、获取当前ip地址

1、获取本地IP

  String ip= InetAddress.getLocalHost().getHostAddress();

2、获取公网IP

    public String getIpv4IP() {
        StringBuilder result = new StringBuilder();
        BufferedReader in = null;
        try {
            URL realUrl = new URL("https://www.taobao.com/help/getip.php");
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
        } catch (Exception e) {
//            log.error("获取ipv4公网地址异常");
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        String str = result.toString().replace("ipCallback({ip:", "");
        String ipStr = str.replace("})", "");

        return ipStr.replace('"', ' ');
    }

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值