JSP验证码随机产生 – 记忆角落

JSP验证码随机产生

/ 2评 / 0

寒假快结束了吧

假期撸多了吧

红包还有吧

-好了吧

入正题


前几天,进了一个清远的政府网站,我无法接受的不是页面好不好看,而是验证码一直卡住

还是 用JSP的-嗯慢慢的想了下我会不会写呢.....嗯我水平真菜

好了上代码

1.先把生成验证码的图片封装为一个JavaBean,这个JavaBean的源代码:

package com.bean;

import java.awt.Color;
import java.awt.Font;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;

import java.util.Random;

import javax.imageio.ImageIO;


/**
 * @author Administrator
 * 生成验证码
 */
public class MakeCertPic {
	//根据以下字母数字生成,已经把一些容易混淆的删除如:i,l,1,0,o
	private char mapTable[]={
		'a','b','c','d','e','f',
		'g','h','j','k',
		'm','n','q','p','r',
		's','t','u','v','w','x',
		'y','z','2','3','4','5',
		'6','7','8','9'};
/*
 * 功能:生成彩色验证图片
 * 参数width为生成图片的宽度,height为图片高度,os为页面输出流
 */
	public String getCertpic(int width,int height,OutputStream os){
		if(width<=0){
			width=60;
		}
		if(height<=0){
			height=20;
		}
		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
		//获取图像上下文
		Graphics g =image.getGraphics();
		//设置背景颜色
		g.setColor(new Color(0xDCDCDC));
		g.fillRect(0, 0, width, height);
		//边框
		g.setColor(Color.black);
		g.drawRect(0, 0, width-1, height-1);
		//取随机验证码
		String strEnsure = "";
		
		//4代表4为验证码,如需要可做修改
		for(int i =0;i<4;++i){
			strEnsure +=mapTable[(int)(mapTable.length*Math.random())];
		}
		g.setColor(Color.black);
		g.setFont(new Font("Atlantic Inline",Font.PLAIN,18));
		String str =strEnsure.substring(0,1);
		g.drawString(str,8,17);
		str = strEnsure.substring(1, 2);

		g.drawString(str,20,15);
		str = strEnsure.substring(2, 3);
		
		g.drawString(str,35,18);
		str = strEnsure.substring(3, 4);
		
		g.drawString(str,45,15);
		//产生10个干扰点
		Random rand = new Random();
		for(int i=0;i<10;i++){
			int x =rand.nextInt(width);
			int y =rand.nextInt(height);
			g.drawOval(x, y, 1, 1);
		}
		//释放图形上下文
		g.dispose();
		try{
			ImageIO.write(image, "JPEG", os);
		}catch (IOException e) {
			// TODO: handle exception
			return "";
		}
		return strEnsure;
		
	}
}

为了造成一些干扰,我随机花了10个干扰点,如果想多点,可以在for循环那个自己加大。

2.在编写一个servlet输出生成的验证码,代码如下:

package com.bean;


import java.io.IOException;

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

public class ShowCertPic extends HttpServlet {
	
	public void service(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException{
		MakeCertPic image =new MakeCertPic();
		String str = image.getCertpic(0, 0, response.getOutputStream());
		request.getSession().setAttribute("certCode2", str);
	}
	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}

3.在web.xml部署应该会了吧,但是我为了方便是直接把url-pattern为/ShowCertPic

最后就是登录的JSP代码,这个你们随便测试就好了

<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
 <head>
 <base href="<%=basePath%>">
 
 <title>登录页面</title>
 
 <meta http-equiv="pragma" content="no-cache">
 <meta http-equiv="cache-control" content="no-cache">
 <meta http-equiv="expires" content="0"> 
 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
 <meta http-equiv="description" content="This is my page">
 <!--
 <link rel="stylesheet" type="text/css" href="styles.css">
 -->
 <script type="text/JavaScript" language="javascript">
 function change(){
 var o = document.getElementById("random");
 var timenow = new Date().getTime();
 o.src = "<%=path%>/ShowCertPic?d=" + timenow;
 }
</script>
 </head>
 
 <body>
 <form action="index.jsp" method="post">
 <h1>系统登录测试</h1>
 <p>
 用户名:
 <input type="text" name="username" />
 </p> 
 <p>
 密码:
 <input type="password" name="password" />
 </p> 
 <p>
 验证码:
 <input type="password" name="certCode" />
 <img alt="code" id="random" src="ShowCertPic">
 <input type="button" value="换一张图片" id="label" onclick="change()"></input>
 </p> 
 <input type="submit" value="登录">
 </form>
 </body>
</html>

随机生成的代码为:

<img alt="code" src="ShowCertPic">

点击更新验证码代码为:

<script type="text/JavaScript" language="javascript">
 function change(){
 var o = document.getElementById("random");
 var timenow = new Date().getTime();
 o.src = "<%=path%>/ShowCertPic?d=" + timenow;
 }
</script>

运行结果图:

我知道你会说,随便打上去也可以吧

那么你可以去做一个验证是否正确,代码我自己瞧这个的

? <%
 String certCode = request.getParameter("certCode");
 String certCode2 = (String)session.getAttribute("certCode2");
 if(certCode != null && certCode2 != null){ 
 if(certCode.equals(certCode2)){ 
 out.println("验证码输入正确!"); 
 }else{ 
 out.println("验证码输入不正确,请重新输入!"); 
 } 
 }
 %>

2条回应:“JSP验证码随机产生”

  1. gg说道:

    刚刚需要用到

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注