jsp实现随机生成验证码代码

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
  <servlet>
  	<servlet-name>CheckcodeServlet</servlet-name>
  	<servlet-class>cn.com.leadfar.cms.backend.view.CheckcodeServlet</servlet-class>
  	<init-param>
  		<param-name>width</param-name>
  		<param-value>44</param-value>
  	</init-param>
  	
  	<init-param>
  		<param-name>height</param-name>
  		<param-value>20</param-value>
  	</init-param>
  	
  	<init-param>
  		<param-name>number</param-name>
  		<param-value>4</param-value>
  	</init-param>
  	
  	<init-param>
  		<param-name>codes</param-name>
  		<param-value>ABCDEFGHIJKLMNOPQRSTUVWXYZ</param-value>
  	</init-param>
  </servlet>
  
  <servlet-mapping>
  	<servlet-name>CheckcodeServlet</servlet-name>
  	<url-pattern>/backend/images/checkcode.jpg</url-pattern>
  </servlet-mapping>
</web-app>


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/backend/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
	<base href="<%=basePath%>">
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<title>CMS 后台管理工作平台</title>
	<link rel="stylesheet" type="text/css" href="css/style.css"/>
	<script type="text/javascript" src="js/js.js"></script>
	<script type="text/javascript">
		function reloadcheckcode(img)
		{
			img.src = "images/checkcode.jpg?" + Math.random();
		}
	</script>
</head>
<body>
<div id="top"> </div>
<form id="login" action="main.jsp" method="post">
  <div id="center">
    <div id="center_left"></div>
    <div id="center_middle">
      <div class="user">
        <label>用户名:
        <input type="text" name="user" id="user" />
        </label>
      </div>
      <div class="user">
        <label>密 码:
        <input type="password" name="pwd" id="pwd" />
        </label>
      </div>
      <div class="chknumber">
        <label>验证码:
        <input name="chknumber" type="text" id="chknumber" maxlength="4" class="chknumber_input" />
        </label>
        <img src="images/checkcode.jpg" id="safecode" onclick = "reloadcheckcode(this)" title = "如果看不清,请点击本图片换一张"/>
      </div>
    </div>
    <div id="center_middle_right"></div>
    <div id="center_submit">
      <div class="button"> <img src="images/dl.gif" width="57" height="20" οnclick="form_submit()" > </div>
      <div class="button"> <img src="images/cz.gif" width="57" height="20" οnclick="form_reset()"> </div>
    </div>
    <div id="center_right"></div>
  </div>
</form>
<div id="footer">北京领航致远科技有限公司</div>
</body>
</html>


package cn.com.leadfar.cms.backend.view;

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

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class CheckcodeServlet extends HttpServlet 
{
	private int width;
	private int height;
	private int number; //显示多少个字符
	private String codes; //有哪些字符可供选择
	
    public CheckcodeServlet() 
    {
        super();
        // TODO Auto-generated constructor stub
    }

	public void init(ServletConfig config) throws ServletException 
	{
		// TODO Auto-generated method stub
		super.init(config);
		width = Integer.parseInt(config.getInitParameter("width"));
		height = Integer.parseInt(config.getInitParameter("height"));
		number = Integer.parseInt(config.getInitParameter("number"));
		codes = config.getInitParameter("codes");
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		// TODO Auto-generated method stub
		response.setContentType("image/jpeg");
		
		//创建一张图片
		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
		Graphics2D g = image.createGraphics();
		
		//创建白色背景
		g.setColor(Color.WHITE);
		//画一个矩形
		g.fillRect(0, 0, width, height);
		//画黑边框
		g.setColor(Color.BLACK);
		g.drawRect(0, 0, width-1, height-1);
		
		Random random = new Random();
		
		//随机生成字符
		for(int i = 0;i < number;i++)
		{
			//每个字符占据的宽度
			int x = (width -1) / number;
			int y = height - 5; 
					
			
			//范围0-length之间不包括length
			String code = String.valueOf(codes.charAt(random.nextInt(codes.length())));
			int red = random.nextInt(256);
			int green = random.nextInt(256);
			int blue = random.nextInt(256);
			
			g.setColor(new Color(red,green,blue));
			
			Font font = new Font("Arial",Font.PLAIN,random(height / 2,height));
			g.setFont(font);
			
			g.drawString(code, i * x + 2, y);
			
		}
		
		//随机生成一些点
		for(int i = 0; i < 50 ;i++)
		{
			int red = random.nextInt(256);
			int green = random.nextInt(256);
			int blue = random.nextInt(256);
			g.setColor(new Color(red,green,blue));
			g.drawOval(random.nextInt(width), random.nextInt(height), 1, 1);
			
		}
		
		
		OutputStream out = response.getOutputStream();
		//将图片转换为JPEG类型
		JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
		encoder.encode(image);
		
		out.flush();
		out.close();
	}

	/**
	 * 产生一个从min到max之间的随机数
	 * @param min
	 * @param max
	 * @return
	 */
	private int random(int min,int max)
	{
		int m = new Random().nextInt(999999) % (max - min);
		return m + min;
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		// TODO Auto-generated method stub
	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值