java实现验证码

java实现验证码

1.html页面


<img onClick="changeCode()" style="height:22px;"id="codeImg" alt="点击更换"
title="点击更换" src="" />



2.Js部分


<script type="text/javascript">
function changeCode() {
var time = new Date();
var codeImg = document.getElementById("codeImg");
codeImg.src = "code?t="+time.getTime();//没有用时间戳清除缓存的话就一直是第一次生成的图片
}
</script>




3.Servlet(后端)

public class Code extends HttpServlet {
 
protected void doGet(HttpServletRequestrequest, HttpServletResponse response) throws ServletException, IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();//字节数组
String code = drawImg(output);
try {
ServletOutputStream out = response.getOutputStream();//向浏览器输出流
output.writeTo(out);//将此字节数组输出流(output)的全部内容写入到指定的输出流参数(out)中。
} catch (IOExceptione) {
e.printStackTrace();
}
}
protected void doPost(HttpServletRequestrequest, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
//生成二维码图片
private String drawImg(ByteArrayOutputStreamoutput){
String code = "";
for(int i=0;i<4; i++){//获取4位随机数
code += randomChar();
}
int width = 70;
int height = 25;
/**
 * TYPE_3BYTE_BGR
          表示一个具有 8 位 RGB 颜色分量的图像,对应于 Windows 风格的 BGR 颜色模型,
          具有用 3 字节存储的 Blue、Green 和 Red 三种颜色。
 */
BufferedImage bi = new BufferedImage(width,height,BufferedImage.TYPE_3BYTE_BGR);
Font font = new Font("Times New Roman",Font.PLAIN,20);//根据指定名称、样式和磅值大小,创建一个新 Font。
Graphics2D g = bi.createGraphics();//创建绘图对象
g.setFont(font);
Color color = new Color(66,2,82);
g.setColor(color);
g.setBackground(new Color(226,226,240));
g.clearRect(0, 0, width, height);//擦除矩形块,清除掉原来的
FontRenderContext context = g.getFontRenderContext();
Rectangle2D bounds = font.getStringBounds(code, context);//设置字体偏移
double x = (width -bounds.getWidth()) / 2;
double y = (height -bounds.getHeight()) / 2;
double ascent =bounds.getY();
double baseY =y - ascent;
g.drawString(code, (int)x, (int)baseY);//绘制文本
g.dispose();//释放由此 Window、其子组件及其拥有的所有子组件所使用的所有本机屏幕资源。即这些 Component 的资源将被破坏,它们使用的所有内存都将返回到操作系统,并将它们标记为不可显示。
try {
/**
 * 使用支持给定格式的任意 ImageWriter 将一个图像写入 File。如果已经有一个 File 存在,则丢弃其内容。
 * im - 要写入的 RenderedImage。
   formatName - 包含格式非正式名称的 String。
   output - 将在其中写入数据的 File。
 */
ImageIO.write(bi, "jpg", output);
} catch (IOExceptione) {
e.printStackTrace();
}
return code;
}
//四位随机数
private char randomChar(){
Random r = new Random();
String s = "ABCDEFGHJKLMNPRSTUVWXYZ0123456789";//33位
return s.charAt(r.nextInt(s.length()));//生成随机数0-32,转为字符,即字母或数字(到33就会破上限报错)
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值