java生成图片验证码




import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;


import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class VerifyCodeServlet  extends HttpServlet{
private static final long serialVersionUID = 1L;
   @Override
   protected void doGet(HttpServletRequest req, HttpServletResponse resp)
           throws ServletException, IOException {
       //图像数据缓冲区  构造函数 第一个参数为宽 第二个参数为高  第三个为图片类型
       BufferedImage bi = new BufferedImage(100, 25, BufferedImage.TYPE_INT_RGB);
       //绘制图片
       Graphics grap = bi.getGraphics();
       //设置字体
       Font f = new Font("宋体",Font.ITALIC ,20); 
       grap.setFont(f);
       //背景颜色
       Color color = new Color(200,160,255);
       //设置背景颜色
       grap.setColor(color);
       grap.fillRect(0, 0, 100, 25);//坐标  绘制图片宽、高
       //验证码内容
       char[] content = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
       Random ran = new Random();//根据随机数来取组合验证码内容
       int len = content.length,index;
       StringBuffer generateCode = new StringBuffer();//存储随机生成的验证码
       //生成6位的验证码
       for(int i = 0;i<4;i++){
           index = ran.nextInt(len);
           //设置验证码颜色
           grap.setColor(new Color(ran.nextInt(100), ran.nextInt(180),ran.nextInt(255)));
           //将字符画在画板上
           grap.drawString(String.valueOf(content[index]), i*16+3, 19);
           generateCode.append(content[index]);
       }
       //将生成的验证码放在session中以便之后验证用到
       req.getSession().setAttribute("verifyCode", generateCode.toString());
       //将生成的验证码图片输出
       ImageIO.write(bi, "PNG", resp.getOutputStream());
   }
   @Override
   protected void doPost(HttpServletRequest req, HttpServletResponse resp)
           throws ServletException, IOException {
       this.doGet(req, resp);
   }

}



需要在web.xml里配置该servlet

<servlet>
<servlet-name>verifyCode</servlet-name>
<servlet-class>com.XXX.VerifyCodeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>verifyCode</servlet-name>
<url-pattern>/common/verifyCode</url-pattern>
</servlet-mapping>

在需要显示验证码的地方指向该servlet

        <img id="VerifyImage" src="/common/verifyCode?r=" + Math.random()" class="seach_btn_pic" title="看不清?点击换一个" οnclick="javascript: document.getElementById('VerifyImage').src = '/common/verifyCode?r=' + Math.random(); return false;" height="24" width="61">
        <a class="seach_hyzs" οnclick="javascript: document.getElementById('VerifyImage').src = '/common/verifyCode?r=' + Math.random(); return false;">换一张</a>



验证码生成后,校验验证码



import javax.servlet.http.HttpServletRequest;


import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;


import com.cqliving.tool.common.Response;



@Controller
@RequestMapping("/validate")
public class ValidateCodeController {

    @ResponseBody
    @RequestMapping(value ="validateCode", method = {RequestMethod.POST,RequestMethod.GET})
    public Response<Void> validateCode(HttpServletRequest request,  @RequestParam(value = "validateCode", required=true) String validateCode){
    Response<Void> res = Response.newInstance();
    String oldCode = (String) request.getSession().getAttribute("verifyCode");
    if (!StringUtils.isEmpty(oldCode)) {
    oldCode = oldCode.toLowerCase();
    }
    if(!StringUtils.isEmpty(validateCode) && oldCode.equals(validateCode.toLowerCase())) {
    res.setCode(0);
    } else {
    res.setCode(1);
    }
    return res;
    }
}



import javax.servlet.http.HttpServletRequest;


import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;


import com.cqliving.tool.common.Response;


/**
 * 
 * 用途:验证码校验
 * 版权所有: 重庆华龙网集团有限公司
 * 项目名称: CMS发布系统
 * 文件名称: com.cqliving.cloud.controller.common.ValidateCodeController.java
 * 创   建  人: clj
 * 创建日期: 2016年11月17日上午10:53:56
 * 最后修改: 保持以下格式
 * -----修改人-----修改日期-----------------修改内容--------------------------------------<br/>
 *
 *
 *
 */
@Controller
@RequestMapping("/validate")
public class ValidateCodeController {

    @ResponseBody
    @RequestMapping(value ="validateCode", method = {RequestMethod.POST,RequestMethod.GET})
    public Response<Void> validateCode(HttpServletRequest request,  @RequestParam(value = "validateCode", required=true) String validateCode){
    Response<Void> res = Response.newInstance();
    String oldCode = (String) request.getSession().getAttribute("verifyCode");
    if (!StringUtils.isEmpty(oldCode)) {
    oldCode = oldCode.toLowerCase();
    }
    if(!StringUtils.isEmpty(validateCode) && oldCode.equals(validateCode.toLowerCase())) {
    res.setCode(0);
    } else {
    res.setCode(1);
    }
    return res;
    }
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

8一天不

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值