JSP中使用验证码

本例子示范在用户登录页面中使用验证码,验证码使用javabena和servlet生成如下:

MakeCertPic.java

package cert;

import java.awt.Color;
import java.awt.Font;
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 Welins 生成验证码图片
*/
public class MakeCertPic {
// 验证码图片中可以出现的字符集,可根据须要修改
private char mapTable[] = {‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘, ‘f‘, ‘0‘, ‘2‘, ‘3‘,
‘4‘, ‘5‘, ‘6‘, ‘7‘, ‘8‘,‘9‘,‘A‘,‘B‘,‘C‘,‘D‘,‘E‘};

/**
* 功能:生成彩色验证码图片 参数width为生成图片的宽度,参数Height为生成图片的高度,参数Os为页面的输出流
*
*/
public String getCertPic(int width, int height, OutputStream os) {
if (width <= 0) {
width = 60;
}
if (height <= 0) {
height = 20;
}
/**
* BufferedImage是Image的一个子类,BufferedImage生成的图片在内存里有一个图像缓冲区,
* 利用这个缓冲区我们可以很方便的操作这个图片,通常用来做图片修改操作如大小变换、图片变灰、设置图片透明或不透明等。
* (500,500,BufferedImage.TYPE_INT_RGB)是什么意思呢? BufferedImage(int width,
* int height, int imageType) width : width of the created image height
* : height of the created image imageType : type of the created image
*
* BufferedImage.TYPE_INT_RGB : 表示一个图像,该图像具有整数像素的 8 位 RGB 颜色
*/
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
/**
* 获取图形的上下文 创建一支画笔g
*/
Graphics g = image.getGraphics();
// 设定背景颜色
g.setColor(new Color(0xDCDCDC));
// 起始x坐标,起始y坐标,图片宽带,图片高度
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++) {
// 随机得到mapTable.length*Math.random()里面的下标,数组mapTable再通过下标把值取出来
strEnsure = strEnsure
+ mapTable[(int) (mapTable.length * Math.random())];

}
// 将验证码现实到图像中,如果要生成更多位的验证码,增加drawString语句
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, 30, 16);
str = strEnsure.substring(3, 4);
g.drawString(str, 45, 17);
// 随机产生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, 2, 4);
}
// 释放图形上下文
g.dispose();
try {
// 输出图像到页面
ImageIO.write(image, "JPEG", os);
} catch (IOException e) {
return "";
}
return strEnsure;

}

}

ShowCertPic.java

package cert;

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 {

@Override
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
// super.service(req, resp);
MakeCertPic image = new MakeCertPic();
String str = image.getCertPic(0, 0, resp.getOutputStream());
// 将验证码存入session
req.getSession().setAttribute("certCode2", str);
}

}

web.xml文件的配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name></display-name>
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>

<servlet>
<servlet-name>ShowCertPic</servlet-name>
<servlet-class>cert.ShowCertPic</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ShowCertPic</servlet-name>
<url-pattern>/ShowCertPic</url-pattern>
</servlet-mapping>

 

</web-app>

登录页面,login.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="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">
-->

</head>

<body>
<form action="logincheck.jsp" method="post">
<table align="center">
<tr align="center">
<td>系统登录</td>
</tr>
<tr>
<td>用户名:<input type="text" name="username">
</td>
</tr>
<tr>
<td>密码:&nbsp;&nbsp;<input type="password" name="password">
</td>
</tr>
<tr>
<td>验证码:<input type="text" name="certCode"><img
id="certcode" src="ShowCertPic" alt="验证码" onclick="this.src=‘ShowCertPic‘">
</td>
</tr>
<tr align="left">
<td><input type="submit" value="提交">
</td>

</tr>
</table>


</form>

 

</body>
</html>

登录的验证码简单处理:

<%@ page language="java" import="java.util.*" pageEncoding="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">
-->

</head>

<body>
<%
String certCode = request.getParameter("certCode");
String certCode2 = (String) session.getAttribute("certCode2");
if (certCode.equals(certCode2)) {
out.print("验证码正确");
} else {
out.print("验证码错误");
}
%>


</body>
</html>

完毕,哪里出现的问题,请大神吗多多赐教哈~

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。