精华内容
下载资源
问答
  • java生成图形验证码

    2017-11-09 14:54:28
    java生成图形验证码

    1.开发所需jar包

    commons-codec-1.10.jar
    commons-lang-2.5.jar
    log4j-1.2.17.jar

    2.图形验证码工具类代码

    import java.awt.BasicStroke;
    import java.awt.Color;
    import java.awt.Font;
    import java.awt.Graphics2D;
    import java.awt.RenderingHints;
    import java.awt.geom.QuadCurve2D;
    import java.awt.image.BufferedImage;
    import java.io.IOException;
    import java.util.Random;
    
    import javax.imageio.ImageIO;
    import javax.servlet.ServletOutputStream;
    import javax.servlet.http.Cookie;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.apache.commons.codec.digest.DigestUtils;
    import org.apache.commons.lang3.StringUtils;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    public class CaptchaUtils {
    
        private static final Logger LOG = LoggerFactory.getLogger(CaptchaUtils.class);
        private static String captchaName = "captcha";
        private static final CaptchaUtils INSTANCE = new CaptchaUtils();
    
        // 默认的验证码大小
        private static final int WIDTH = 100, HEIGHT = 46;
        // 验证码随机字符数组
        private static final String[] strArr = { "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H",
                "J", "K", "M", "N", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y" };
        // 验证码字体
        private static final Font[] RANDOM_FONT = new Font[] {
            new Font("nyala", Font.BOLD, 38),
            new Font("Arial", Font.BOLD, 32),
            new Font("Bell MT", Font.BOLD, 32),
            new Font("Credit valley", Font.BOLD, 34),
            new Font("Impact", Font.BOLD, 32),
            new Font(Font.MONOSPACED, Font.BOLD, 40)
        };
    
        public static CaptchaUtils getInstance() {
            return INSTANCE;
        }
    
        /**
         * 生成验证码
         * 
         * @throws IOException
         */
        public void render(HttpServletResponse response) throws IOException,Exception {
            BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
            String vCode = drawGraphic(image);
            vCode = vCode.toUpperCase(); // 转成大写重要
            System.out.println(vCode);
            vCode = DigestUtils.md5Hex(vCode);
            Cookie cookie = new Cookie(captchaName, vCode);
            cookie.setMaxAge(-1);
            cookie.setPath("/");
            try {
                // try catch 用来兼容不支持 httpOnly 的 tomcat、jetty
                cookie.setHttpOnly(true);
            } catch (Exception e) {
                LOG.error("", e);
            }
            response.addCookie(cookie);
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            response.setContentType("image/jpeg");
    
            ServletOutputStream sos = null;
            try {
                sos = response.getOutputStream();
                ImageIO.write(image, "jpeg", sos);
            } catch (IOException e) {
                throw e;
            } catch (Exception e) {
                throw e;
            } finally {
                if (sos != null) {
                    try {
                        sos.close();
                    } catch (IOException e) {
                        LOG.error("", e);
                    }
                }
            }
        }
    
        private String drawGraphic(BufferedImage image) {
            // 获取图形上下文
            Graphics2D g = image.createGraphics();
    
            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
            // 图形抗锯齿
            g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            // 字体抗锯齿
            g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    
            // 设定背景色
            g.setColor(getRandColor(200, 250));
            g.fillRect(0, 0, WIDTH, HEIGHT);
    
            // 生成随机类
            Random random = new Random();
            // 设定字体
            g.setFont(RANDOM_FONT[random.nextInt(RANDOM_FONT.length)]);
    
            // 画蛋蛋,有蛋的生活才精彩
            Color color;
            for (int i = 0; i < 10; i++) {
                color = getRandColor(120, 200);
                g.setColor(color);
                g.drawOval(random.nextInt(WIDTH), random.nextInt(HEIGHT), 5 + random.nextInt(10), 5 + random.nextInt(10));
                color = null;
            }
    
            // 取随机产生的认证码(4位数字)
            String sRand = "";
            for (int i = 0; i < 4; i++) {
                String rand = String.valueOf(strArr[random.nextInt(strArr.length)]);
                sRand += rand;
                // 旋转度数 最好小于45度
                int degree = random.nextInt(28);
                if (i % 2 == 0) {
                    degree = degree * (-1);
                }
                // 定义坐标
                int x = 22 * i, y = 21;
                // 旋转区域
                g.rotate(Math.toRadians(degree), x, y);
                // 设定字体颜色
                color = getRandColor(20, 130);
                g.setColor(color);
                // 将认证码显示到图象中
                g.drawString(rand, x + 8, y + 10);
                // 旋转之后,必须旋转回来
                g.rotate(-Math.toRadians(degree), x, y);
                color = null;
            }
            // 图片中间线
            g.setColor(getRandColor(0, 60));
            // width是线宽,float型
            BasicStroke bs = new BasicStroke(3);
            g.setStroke(bs);
            // 画出曲线
            QuadCurve2D.Double curve = new QuadCurve2D.Double(0d, random.nextInt(HEIGHT - 8) + 4, WIDTH / 2, HEIGHT / 2,
                    WIDTH, random.nextInt(HEIGHT - 8) + 4);
            g.draw(curve);
            // 销毁图像
            g.dispose();
            return sRand;
        }
    
        /*
         * 给定范围获得随机颜色
         */
        private Color getRandColor(int fc, int bc) {
            Random random = new Random();
            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);
        }
    
        /**
         * 仅能验证一次,验证后立即销毁 cookie
         * @param controller 控制器
         * @param userInputCaptcha 用户输入的验证码
         * @return 验证通过返回 true, 否则返回 false
         */
        public boolean validate(HttpServletRequest request, HttpServletResponse response, String userInputCaptcha) {
            if (StringUtils.isEmpty(userInputCaptcha)) {
                return false;
            }
    
            request.getCookies();
    
            userInputCaptcha = userInputCaptcha.toUpperCase();  // 转成大写重要
            userInputCaptcha = DigestUtils.md5Hex(userInputCaptcha);
            boolean result = userInputCaptcha.equals(getCookie(request, captchaName));
            if (result == true) {
                removeCookie(response, captchaName);
            }
            return result;
        }
    
        private String getCookie(HttpServletRequest request, String name) {
            Cookie[] cookies = request.getCookies();
            String value = null;
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(name)) {
                    value = cookie.getValue();
                    break;
                }
            }
            return value;
        }
    
    
        private void removeCookie(HttpServletResponse response, String name) {
            Cookie cookie = new Cookie(captchaName, StringUtils.EMPTY);
            cookie.setHttpOnly(true);
            cookie.setMaxAge(0);            // 0:delete
            cookie.setPath("/");
            response.addCookie(cookie);
        }
    }

    3.调用图形验证码

        @RequestMapping(value="/captcha")
        public void captcha(HttpServletRequest request, HttpServletResponse response) {
            try {
                CaptchaUtils.getInstance().render(response);
            } catch(IOException e) {
                LOGGER.error("", e);
            } catch(Exception e) {
                LOGGER.error("", e);
            }
        }

    4.效果
    大小:100*46
    这里写图片描述

    展开全文
  • Java生成图形验证码

    千次阅读 2018-08-04 11:49:29
        验证码是一种区分用户是计算机还是人的公共全自动程序。...     图形验证码是最传统的一种的验证码形式,都是由后台进行生成绘制的,...下面贴下生成图形验证码Java代码(该代码运行后会生成JFrame窗口...

        验证码是一种区分用户是计算机还是人的公共全自动程序。可以防止:恶意破解密码、刷票、论坛灌水,有效防止某个黑客对某一个特定注册用户用特定程序暴力破解方式进行不断的登陆尝试的操作。
        图形验证码是最传统的一种的验证码形式,都是由后台进行生成绘制的,生成过程要考虑到机器识别的可能性,因此要添加干扰线来扰乱机器的识别。下面贴下生成图形验证码的Java代码(该代码运行后会生成JFrame窗口显示验证码,若要传到前台通过ImageIO.write()方法实现)。

    import java.awt.*;
    import java.util.Random;
    
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    
    public class ToolVerificationCode extends JPanel {
        final private int width     = 60;      // 图片的宽度
        final private int height    = 20;      // 图片的高度
        final private int codeCount = 4;       // 验证码字符个数
        final private int lineCount = 200;     // 验证码干扰线数
    
        final private static char[] charCode = {
                // 去掉 'O'、'o'、'0'、'I'、'i'、'L'、'l'、'1'
                'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W','X', 'Y', 'Z',
                'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w','x', 'y', 'z',
                '2', '3', '4', '5', '6', '7', '8', '9'
        };
    
        private static final long serialVersionUID = 1L;
    
        /**
         * 生成码
         */
        public ToolVerificationCode createCode(Graphics g) {
            // 创建画笔
            Graphics2D graphics2D = (Graphics2D) g;
            // 填充矩形
            graphics2D.setColor(genRandColor(200, 250));
            graphics2D.fillRect(0, 0, width, height);
            // 画边框
            graphics2D.setColor(genRandColor(0, 20));
            graphics2D.drawRect(0, 0, width - 1, height - 1);
            // 设置字体
            graphics2D.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 15));
            // 干扰线
            Random random = new Random();
            int lineWidth = 2; // 干扰线长度
            for (int i = 0; i < lineCount; i++) {
                graphics2D.setColor(genRandColor(150, 200));
                int x1 = random.nextInt(width - lineWidth - 1) + 1;
                int y1 = random.nextInt(height - lineWidth - 1) + 1;
                int x2 = random.nextInt(lineWidth);
                int y2 = random.nextInt(lineWidth);
                graphics2D.drawLine(x1, y1, x1 + x2, y1 + y2);
            }
            // 生成码
            for (int i = 0; i < codeCount; i++) {
                String str = String.valueOf(charCode[random.nextInt(charCode.length)]);
                graphics2D.setColor(genRandColor(20, 130));
                graphics2D.drawString(str, 15 * i + random.nextInt(5), random.nextInt(5) + 13);
            }
            graphics2D.dispose();
    
            return this;
        }
    
        // 随机颜色范围
        private Color genRandColor(int fc, int bc) {
            Random random = new Random();
            fc = fc > 255 ? 255 : fc;
            bc = bc > 255 ? 255 : bc;
    
            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);
        }
    
        @Override
        public void paint(Graphics g) {
            super.paint(g);
            createCode(g);
        }
    
        public static void main(String[] args) {
            JFrame jFrame = new JFrame();
            jFrame.add(new ToolVerificationCode());
            jFrame.setBounds(0, 0, 200, 100);
            jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            jFrame.setVisible(true);
        }
    
    }

    这里写图片描述

    注:可根据自身需要修改代码。

    展开全文
  • 主要介绍了Java生成图形验证码工具类,本文思路明确介绍的非常详细,需要的朋友可以参考下
  • JAVA生成图形验证码

    2018-03-31 23:33:29
    public void doCreateCodeAction(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setHeader(...JAVA类控制层中验证生成图形验证码↑ 工具类地址: 图形验证码工具类
    public void doCreateCodeAction(HttpServletRequest request, HttpServletResponse response) throws IOException {  
            response.setHeader("Expires", "-1");  
            response.setHeader("Cache-Control", "no-cache");  
            response.setHeader("Pragma", "-1");  
            CaptchaUtil util = CaptchaUtil.Instance();  
            // 将验证码输入到session中,用来验证  
            String code = util.getString();  
            request.getSession().setAttribute("code", code);  
            System.out.println(request.getSession().getAttribute("code"));
            // 输出打web页面  
            ImageIO.write(util.getImage(), "jpg", response.getOutputStream());  
        }  

    ↑在控制层的java类里面写,方便页面读取调用

     <input id="code"         name="std6" class="input2"  type="text" />
    <div class="change_put"><img id="img" src="<spring:url value='/api/doCreateCode' />"  οnclick="refresh()" /></div>
    <button  class="change"  οnclick="refresh()" value="" >换一张</button>

    ↑HTML页面使用


    function refresh() {  
        var url =  "你的路径名?number="+Math.random();  
        $("#img").attr("src",url);
    }  

    js调用↑



    	 private void doCheckCodeAction(HttpSession session, String code) throws UfdmException { 
    	        String codeSession = (String) session.getAttribute("code");  
    	        if (StringUtils.isEmpty(codeSession)) {  //验证在session中获取到的验证码是否为空
    	        	//返回错误信息
    	        }  
    	        if (StringUtils.isEmpty(code)) {  //验证在session中获取到的验证码是否为空
    	        	//返回错误信息
    	        }  
    	        if (!codeSession.equalsIgnoreCase(code)) {  
    	            // 验证码通过  
    	        	
    	        } 
    	    }  
    JAVA类控制层中验证生成的图形验证码↑


    工具类地址:

    图形验证码工具类

    展开全文
  • 生成图形验证码(算数运算图形验证码 + 随机字符图形验证码)

    平凡也就两个字: 懒和惰;
    成功也就两个字: 苦和勤;
    优秀也就两个字: 你和我。
    跟着我从0学习JAVA、spring全家桶和linux运维等知识,带你从懵懂少年走向人生巅峰,迎娶白富美!
    关注微信公众号【 IT特靠谱 】,每天都会分享技术心得~

     

    生成图形验证码(算数运算图形验证码 + 随机字符图形验证码)

    1 场景

          在用户登录、忘记密码、用户注册、修改用户信息....等场景需要对用户进行图形化验证。防止别有用心的人或机器通过接口来进行攻击或恶意操作。

          本示例讲解通过java生成两种图形验证码:算数运算的图形验证码和定长随机字符图形验证码!

     

    2 编写代码

    2.1 创建生成指定长度的随机字符串工具类

          创建生成指定长度的随机字符串工具类:RandomCodeUtil.java,该工具类在之前的博客中讲到过。

    import java.util.Random;
    
    /**
     * 生成指定长度的随机字符串
     */
    public class RandomCodeUtil {
    
      /**
       * 生成指定长度的随机字符串(不包含数字0,和字母l、o和i)
       *
       * @param capacity 验证码长度
       */
      public static String genCode(Integer capacity) {
        //随机字符集(不包含数字0和字母o、i和l)
        String str = "abcdefghjkmnpqrstuvwxyz123456789";
        Random rand = new Random();
        StringBuilder a = new StringBuilder();
        for (int i = 0; i < capacity; i++) {
          char c = str.charAt(rand.nextInt(str.length()));
          a.append(c);
        }
        return a.toString();
      }
    
      public static void main(String[] args) {
        //生产6位长度的随机验证码
        System.out.println(RandomCodeUtil.genCode(6));
      }
    }

     

    2.2 创建图形验证码工具类

          创建图形验证码工具类:ImgCodeUtil.java

    import java.awt.Color;
    import java.awt.Font;
    import java.awt.Graphics2D;
    import java.awt.image.BufferedImage;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.OutputStream;
    import java.util.Random;
    import javax.imageio.ImageIO;
    
    /**
     * 生成图形验证码工具类
     */
    public class ImgCodeUtil {
    
      /**
       * 图片的宽度
       */
      private Integer width = 120;
    
      /**
       * 图片的高度
       */
      private Integer height = 40;
    
      /**
       * 验证码干扰线条数
       */
      private Integer lineCount = 8;
    
      /**
       * 验证码code
       */
      private String validateCode = null;
    
      /**
       * 验证码图片Buffer
       */
      private BufferedImage buffImg = null;
    
      /**
       * 构造方法
       */
      public ImgCodeUtil(String validateCode) {
        this.validateCode = validateCode;
        this.createCode();
      }
    
      /**
       * 构造方法
       */
      public ImgCodeUtil(String validateCode, int width, int height) {
        this.width = width;
        this.height = height;
        this.validateCode = validateCode;
        this.createCode();
      }
    
      /**
       * 生成验证码图片
       */
      private void createCode() {
        int x = 0;
        int fontHeight;
        int codeY = 0;
        int red = 0;
        int green = 0;
        int blue = 0;
        int codeCount = validateCode.length();
        //每个字符的宽度
        x = width / codeCount;
        //字体的高度
        fontHeight = height - 2;
        codeY = height - 4;
    
        // 图像buffer
        buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = buffImg.createGraphics();
        // 生成随机数
        Random random = new Random();
        // 将图像填充为白色
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, width, height);
    
        //图片划线
        for (int i = 0; i < lineCount; i++) {
          int xs = random.nextInt(width / 2);
          int ys = random.nextInt(height);
          int xe = random.nextInt(width / 2) + width / 2;
          int ye = random.nextInt(height);
          red = random.nextInt(255);
          green = random.nextInt(255);
          blue = random.nextInt(255);
          g.setColor(new Color(red, green, blue));
          g.drawLine(xs, ys, xe, ye);
        }
    
        Font font = new Font("Arial", Font.BOLD, fontHeight);
        g.setFont(font);
        // 将验证码写入图片
        for (int i = 0; i < codeCount; i++) {
          red = random.nextInt(255);
          green = random.nextInt(255);
          blue = random.nextInt(255);
          g.setColor(new Color(red, green, blue));
          g.drawString(String.valueOf(validateCode.charAt(i)), i * x, codeY);
        }
      }
    
      /**
       * 输出图片到指定路径
       */
      public void write(String path) throws IOException {
        OutputStream outputStream = new FileOutputStream(path);
        this.write(outputStream);
      }
    
      /**
       * 将图片输出到输出流中
       */
      public void write(OutputStream outputStream) throws IOException {
        ImageIO.write(buffImg, "png", outputStream);
        outputStream.close();
      }
    
      public BufferedImage getBuffImg() {
        return buffImg;
      }
    }

     

    2.3 创建图形验证码接口类

          创建图形验证码接口类:ValidateCodeService.java

    import com.xxx.alltest.dto.CheckCode;
    import com.xxx.alltest.entity.ValidateCode;
    
    /**
     * 图形验证码接口类
     */
    public interface ValidateCodeService {
    
      /**
       * 生成算数运算图形验证码
       */
      ValidateCode generateMathImgCode(Integer width, Integer height);
    
      /**
       * 生成随机字符串图形验证码
       */
      ValidateCode generateRandomImgCode(Integer width, Integer height);
    
      /**
       * 校验图形验证码值
       */
      String checkValidateCode(CheckCode checkCode);
    }

     

    2.4 创建图形验证码接口实现类

          图形验证码接口实现类:ValidateCodeServiceImpl.java

    import com.xxx.alltest.dto.CheckCode;
    import com.xxx.alltest.entity.ValidateCode;
    import com.xxx.alltest.service.ValidateCodeService;
    import com.xxx.alltest.utils.ImgCodeUtil;
    import com.xxx.alltest.utils.RandomCodeUtil;
    import java.awt.image.BufferedImage;
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.util.Objects;
    import java.util.UUID;
    import javax.imageio.ImageIO;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.commons.lang3.RandomUtils;
    import org.springframework.stereotype.Service;
    import org.springframework.util.Base64Utils;
    import org.springframework.util.StringUtils;
    
    /**
     * 图形验证码接口实现类
     */
    @Slf4j
    @Service
    public class ValidateCodeServiceImpl implements ValidateCodeService {
    
      /**
       * 验证码过期时间:5分钟
       */
      private static final Long EXPIRE_TIME = 5 * 60 * 1000L;
    
      /**
       * 生成算数运算图形验证码
       */
      @Override
      public ValidateCode generateMathImgCode(Integer width, Integer height) {
        Integer firstNum = RandomUtils.nextInt() % 10 + 1;
        Integer secondNum = RandomUtils.nextInt() % 10 + 1;
        Integer validateCode = firstNum + secondNum;
        ImgCodeUtil imgCodeUtil = new ImgCodeUtil(firstNum + "+" + secondNum + "=?", width, height);
        BufferedImage buffImg = imgCodeUtil.getBuffImg();
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    
        String base64ImgCode = null;
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        try {
          ImageIO.write(buffImg, "png", byteArrayOutputStream);
          byte[] bytes = byteArrayOutputStream.toByteArray();
          base64ImgCode = Base64Utils.encodeToString(bytes);
          //将生成的验证码缓存起来
    //            redisTemplate.set(String.join(":", "mathImgCode", uuid), validateCode.toString(), EXPIRE_TIME);
        } catch (IOException var10) {
          log.error("生成算数运算图形验证码失败");
        }
        return ValidateCode.builder()
            .base64ImgCode(base64ImgCode)
            .uuid(uuid)
            .build();
      }
    
      /**
       * 生成随机字符串图形验证码
       */
      @Override
      public ValidateCode generateRandomImgCode(Integer width, Integer height) {
        String validateCode = RandomCodeUtil.genCode(4);
        ImgCodeUtil imgCodeUtil = new ImgCodeUtil(validateCode, width, height);
        BufferedImage buffImg = imgCodeUtil.getBuffImg();
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    
        String base64ImgCode = null;
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        try {
          ImageIO.write(buffImg, "png", byteArrayOutputStream);
          byte[] bytes = byteArrayOutputStream.toByteArray();
          base64ImgCode = Base64Utils.encodeToString(bytes);
          //将生成的验证码缓存起来
    //            redisTemplate.set(String.join(":", "randomImgCode", uuid), validateCode, EXPIRE_TIME);
        } catch (IOException var10) {
          log.error("生成随机字符串图形验证码失败");
        }
        return ValidateCode.builder()
            .base64ImgCode(base64ImgCode)
            .uuid(uuid)
            .build();
      }
    
      /**
       * 校验图形验证码值
       */
      @Override
      public String checkValidateCode(CheckCode checkCode) {
        String redisCode = null;
    //        String redisCode = redisTemplate.get(String.join(":", "randomImgCode", checkCode.getUuid()));
        if (StringUtils.isEmpty(redisCode)) {
          return "验证码已过期";
        }
        if (!Objects.equals(checkCode.getValidateCode(), redisCode)) {
          return "验证码错误";
        }
        return null;
      }
    }

     

    2.5 创建验证码相关api接口类

          创建验证码相关api接口类:ValidateCodeController.java

    import com.xxx.alltest.all.oss.common.Result;
    import com.xxx.alltest.dto.CheckCode;
    import com.xxx.alltest.entity.ValidateCode;
    import com.xxx.alltest.service.ValidateCodeService;
    import java.util.Objects;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.util.StringUtils;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RequestBody;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.RestController;
    
    /**
     * 验证码相关api接口
     */
    @RestController
    @RequestMapping("/validate")
    public class ValidateCodeController {
    
      @Autowired
      private ValidateCodeService validateCodeService;
    
      /**
       * 生成图形验证码
       *
       * @param type 0-普通字符图形验证码(如:1a4h)  1-算数图形验证码(1+8=?)
       */
      @GetMapping("generate")
      public Result<ValidateCode> generate(@RequestParam(value = "type", defaultValue = "0") String type,
          @RequestParam(value = "width", defaultValue = "100") Integer width,
          @RequestParam(value = "height", defaultValue = "40") Integer height) {
        ValidateCode validateCode = null;
        if (Objects.equals("0", type)) {
          validateCode = validateCodeService.generateRandomImgCode(width, height);
        } else {
          validateCode = validateCodeService.generateMathImgCode(width, height);
        }
    
        if (StringUtils.isEmpty(validateCode.getBase64ImgCode())) {
          return Result.failed("生成图形验证码失败");
        } else {
          return Result.ok(validateCode);
        }
      }
    
      /**
       * 校验图形验证码
       */
      @PostMapping("check")
      public Result check(@RequestBody CheckCode checkCode) {
        String msg = validateCodeService.checkValidateCode(checkCode);
        if (!StringUtils.isEmpty(msg)) {
          return Result.failed(msg);
        }
        return Result.ok();
      }
    }

          如果你有疑问或需要技术支持,关注公众号联系我吧~

     

    展开全文
  • JAVA 生成图形验证码

    2007-05-15 13:30:00
    /** *//** * 创建图形验证码 */import java.awt.Color;import java.awt.Font;import java.awt.Graphics2D;import java.awt.image.BufferedImage;import java.io.File;import java.util.LinkedList;import...
  • JAVA生成图形验证码并返回给前台,SpringBoot+vue @GetMapping("/createCaptchaImage") public ResultModel getCode(HttpServletResponse response) throws IOException { // 生成随机字串 String verifyCode = ...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 391
精华内容 156
关键字:

java生成图形验证码

java 订阅