java生成在线验证码

Posted 捡黄金的少年

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java生成在线验证码相关的知识,希望对你有一定的参考价值。

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('"', ' ');
    

以上是关于java生成在线验证码的主要内容,如果未能解决你的问题,请参考以下文章

JAVA生成验证码代码

java生成验证码

java验证码-汉字验证码

java web 验证码生成后一般在啥地方保存这个验证码?存到数据库还是怎么地?

Java----前端验证之验证码额实现

java图形验证码生成工具类及web页面校验验证码