Java 验证码设计代码

别烦恼我 贡献于2012-11-04

作者 User  创建于2012-08-18 08:43:00   修改者User  修改于2012-08-18 09:26:00字数1603

文档摘要:Java 验证码设计代码
关键词:

 2、验证码设计程序 package com.libo; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Image; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.io.PrintWriter; 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 CheckCode extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //禁止浏览器缓存图片 response.setDateHeader("Expires",-1) ; response.setHeader("Cache-Control","no-cahce") ; response.setHeader("Pragma","no-cahce") ; //通知客户机以图片的方式打开发送过去的数据 response.setHeader("Content-Type", "image/jpeg") ; //在内存中创建一幅图 BufferedImage img = new BufferedImage(80,30,BufferedImage.TYPE_INT_RGB) ; //向图片上写数据 Graphics g = img.getGraphics() ; //设置背景颜色 g.setColor(Color.red) ; g.fillRect(0, 0, 80, 30) ; //设置写入数据的颜色和背景 g.setColor(Color.black) ; g.setFont(new Font(null,Font.BOLD,20)) ; String nums = nums() ; request.getSession().setAttribute("CheckCode",nums) ; g.drawString(nums, 5, 20) ; //把写好的数据图片输出给浏览器 ImageIO.write(img,"jpg",response.getOutputStream()) ; response.setContentType("text/html,charset=utf-8"); PrintWriter out = response.getWriter(); } public String nums(){ Random rd = new Random() ; String nums =rd.nextInt(999999) +""; StringBuffer sb = new StringBuffer() ; for(int i=0;i<6-nums.length();i++){ sb.append("0") ; } nums = sb.toString() + nums ; return nums; } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response) ; } }

下载文档到电脑,查找使用更方便

文档的实际排版效果,会与网站的显示效果略有不同!!

需要 2 金币 [ 分享文档获得金币 ] 2 人已下载

下载文档