java实现验证码

来源:互联网 发布:libsvm c语言 使用 编辑:程序博客网 时间:2024/06/11 16:41

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
原创粉丝点击