本文主要是介绍加减乘除验证码(java),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
加减乘除验证码(java)
(1)CaptchaUtil .java
package com.durian.common.tool;import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;import javax.imageio.ImageIO;public class CaptchaUtil {public static String[] fuhao = { "+", "-", "*", "/" };public static int num = 0;public static String result = "";// 生成随机算式public static String random() {List list = new ArrayList();Random ran = new Random();int n1 = ran.nextInt(10);int n2 = ran.nextInt(10);String f = fuhao[ran.nextInt(fuhao.length)];StringBuilder sb = new StringBuilder(4);switch (f) {case "+":num = n1 + n2;break;case "-":num = n1 - n2;break;case "*":num = n1 * n2;break;case "/":if (n2 == 0) {n2 = ran.nextInt(10) + 1;num = n1 / n2;} else {num = n1 / n2;}break;}sb.append(n1);sb.append(f);sb.append(n2);sb.append("=");result = num + "";return sb.toString();}public static void outputImage(String str, OutputStream os) {Random ran = new Random();// 创建图片对象BufferedImage img = new BufferedImage(100, 40, BufferedImage.TYPE_INT_RGB);// 获取画布Graphics g = img.getGraphics();// 设置背景g.setColor(Color.white);g.fillRect(0, 0, 100, 40);// 写字g.setColor(Color.black);g.setFont(new Font("微软雅黑", Font.PLAIN, 30));g.drawString(str, 10, 40);// 随机三条线g.drawLine(ran.nextInt(100), ran.nextInt(40), ran.nextInt(100), ran.nextInt(40));g.drawLine(ran.nextInt(100), ran.nextInt(40), ran.nextInt(100), ran.nextInt(40));g.drawLine(ran.nextInt(100), ran.nextInt(40), ran.nextInt(100), ran.nextInt(40));// 4. 输出结果// 常见的压缩格式:jpeg(有损压缩), png(无损压缩) ...try {ImageIO.write(img, "png", os);} catch (IOException e) {e.printStackTrace();}}}
(2)CaptchaServlet.java
package com.durian.amanager.servlet;import java.io.IOException;
import java.util.Date;import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import com.durian.amanager.constant.XConstant;
import com.durian.common.entity.Captcha;
import com.durian.common.tool.CaptchaUtil;
import com.durian.common.tool.IPUtil;/*** 获取验证码* * @author leng**/
@WebServlet(urlPatterns = "/captcha.png")
public class CaptchaServlet extends HttpServlet {private static final Logger logger = LoggerFactory.getLogger(CaptchaServlet.class);@Overrideprotected void service(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {response.setContentType("image/png");// 获取随机字符串String random = CaptchaUtil.random();Captcha captcha = Captcha.build(random, CaptchaUtil.result, new Date());HttpSession session = request.getSession();String sessionId = session.getId();String clientIp = IPUtil.getIpAddr(request);// 存入结果session.setAttribute(XConstant.CAPTCHA, captcha.getResult());// 输出图片CaptchaUtil.outputImage(random, response.getOutputStream());logger.info("获取验证码,客户端IP=" + clientIp + ",sessionId=" + sessionId + ",验证码信息:" + captcha.toJsonObjectString());}
}
(3)Captcha.java
package com.durian.common.entity;import java.io.Serializable;
import java.util.Date;import com.alibaba.fastjson.JSONObject;/*** 验证码实体* * @author leng**/
public class Captcha implements Serializable {/*** 验证码*/private String captcha;/*** 结果*/private String result;/*** 创建时间*/private Date createTime;/*** 超时时间(秒)(默认30分钟)*/private int timeout = 30_000;/*** 构建验证码* * @param captcha 显示内容* @param result 验证码结果* @param createTime 创建时间* @return*/public static Captcha build(String captcha, String result, Date createTime) {Captcha cap = new Captcha();cap.setCaptcha(captcha);cap.setResult(result);cap.setCreateTime(createTime);return cap;}public String getCaptcha() {return captcha;}public void setCaptcha(String captcha) {this.captcha = captcha;}public String getResult() {return result;}public void setResult(String result) {this.result = result;}public Date getCreateTime() {return createTime;}public void setCreateTime(Date createTime) {this.createTime = createTime;}public int getTimeout() {return timeout;}public void setTimeout(int timeout) {this.timeout = timeout;}public String toJsonObjectString() {return JSONObject.toJSONString(this);}}
(4)使用:
<img src="../captcha.png" id="captcha_form_reg" οnclick="this.src ='../captcha.png?t='+new Date().getTime()" />
注意:如果是springboot项目,请确保是否开启了Servlet扫描注解,如果未开启则可能无法访问(如下图示例)。
@ServletComponentScan servlet扫描注解
这篇关于加减乘除验证码(java)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!