欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

图片验证码

程序员文章站 2022-03-04 10:45:50
...

假设有两个jsp和一个java文件。

userLogin.jsp

<tr>
    <td class="STYLE1">
        <span id="check_code">验 证 码:&nbsp;&nbsp;</span>
		<span>
            <img id="imgCheckCode" src="inc/img.jsp" alt="点击刷新验证码" style="cursor:pointer;border:0;height:20px;margin-left:-2px;" onclick="this.src='inc/img.jsp?t='+Math.random()">
        </span>
	</td>
</tr>

img.jsp

<%@page import="com.ufgov.portal.web.util.CheckCode"%>
<%@ page contentType="image/jpeg; charset=UTF-8"
	import="java.awt.*,java.awt.image.*,java.util.*,javax.imageio.*,java.io.*"%>
<%
	response.setHeader("Pragma", "No-cache");
	response.setHeader("Cache-Control", "no-cache");
	response.setDateHeader("Expires", 0);

	BufferedImage image = CheckCode.creatImage(request, response);

	ImageIO.write(image, "JPEG", response.getOutputStream());
	
	out.clear();
	out = pageContext.pushBody();
%>

CheckCode

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class CheckCode
{
  public static BufferedImage creatImage(HttpServletRequest request, HttpServletResponse response)
  {
    int width = 130; int height = 50;

    Random random = new Random();
    BufferedImage image = new BufferedImage(width, height, 
      1);

    Graphics g = image.getGraphics();

    g.fillRect(0, 0, width, height);

    g.setFont(new Font("宋体", 1, 40));

    String str1 = randomStr(4);
    HttpSession session = request.getSession();
    session.setAttribute("rand", str1);
    g.drawString("    ", 0, 0);
    for (int i = 0; i < 4; ++i) {
      String rand = str1.substring(i, i + 1);

      g.setColor(
        new Color(20 + random.nextInt(110), 100 + random.nextInt(110), 
        20 + random.nextInt(110)));

      g.drawString(rand, 25 * i + 20, 40);
    }

    g.dispose();
    return image;
  }

  private static String randomStr(int n)
  {
    String str1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
    String str2 = "";
    int len = str1.length() - 1;

    for (int i = 0; i < n; ++i) {
      double r = Math.random() * len;
      str2 = str2 + str1.charAt((int)r);
    }
    return str2;
  }
}

 

转载于:https://my.oschina.net/beborn/blog/834081

上一篇: 捉摸Python的WSGI

下一篇: WSGI协议