JSP + Servlet实现生成登录验证码示例
作者:Giving_bestself 时间:2023-06-27 02:47:59
随机生成四位数验证码,包括汉字,数字,英文大小写。
1.Servlet类
package servlet;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.geom.Line2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class PictureCheckCode extends HttpServlet {
private static final long serialVersionUID = 1L;
public PictureCheckCode() {
super();
}
public void destroy() {
super.destroy();
}
public void init() throws ServletException {
super.init();
}
/*该方法主要作用是获得随机生成的颜色*/
public Color getRandColor(int s,int e){
Random random=new Random ();
if(s>255) s=255;
if(e>255) e=255;
int r,g,b;
r=s+random.nextInt(e-s); //随机生成RGB颜色中的r值
g=s+random.nextInt(e-s); //随机生成RGB颜色中的g值
b=s+random.nextInt(e-s); //随机生成RGB颜色中的b值
return new Color(r,g,b);
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("this is doGet method");
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//设置不缓存图片
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "No-cache");
response.setDateHeader("Expires", 0);
//指定生成的响应图片,一定不能缺少这句话,否则错误.
response.setContentType("image/jpeg");
int width=80,height=35; //指定生成验证码的宽度和高度
BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB); //创建BufferedImage对象,其作用相当于一图片
Graphics g=image.getGraphics(); //创建Graphics对象,其作用相当于画笔
Graphics2D g2d=(Graphics2D)g; //创建Grapchics2D对象
Random random=new Random();
Font mfont=new Font("楷体",Font.BOLD,16); //定义字体样式
g.setColor(getRandColor(200,250));
g.fillRect(0, 0, width, height); //绘制背景
g.setFont(mfont); //设置字体
g.setColor(getRandColor(180,200));
//绘制100条颜色和位置全部为随机产生的线条,该线条为2f
for(int i=0;i<100;i++){
int x=random.nextInt(width-1);
int y=random.nextInt(height-1);
int x1=random.nextInt(6)+1;
int y1=random.nextInt(12)+1;
BasicStroke bs=new BasicStroke(2f,BasicStroke.CAP_BUTT,BasicStroke.JOIN_BEVEL); //定制线条样式
Line2D line=new Line2D.Double(x,y,x+x1,y+y1);
g2d.setStroke(bs);
g2d.draw(line); //绘制直线
}
//输出由英文,数字,和中文随机组成的验证文字,具体的组合方式根据生成随机数确定。
String sRand="";
String ctmp="";
int itmp=0;
//制定输出的验证码为四位
for(int i=0;i<4;i++){
switch(random.nextInt(3)){
case 1: //生成A-Z的字母
itmp=random.nextInt(26)+65;
ctmp=String.valueOf((char)itmp);
break;
case 2: //生成汉字
String[] rBase={"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"};
//生成第一位区码
int r1=random.nextInt(3)+11;
String str_r1=rBase[r1];
//生成第二位区码
int r2;
if(r1==13){
r2=random.nextInt(7);
}else{
r2=random.nextInt(16);
}
String str_r2=rBase[r2];
//生成第一位位码
int r3=random.nextInt(6)+10;
String str_r3=rBase[r3];
//生成第二位位码
int r4;
if(r3==10){
r4=random.nextInt(15)+1;
}else if(r3==15){
r4=random.nextInt(15);
}else{
r4=random.nextInt(16);
}
String str_r4=rBase[r4];
//将生成的机内码转换为汉字
byte[] bytes=new byte[2];
//将生成的区码保存到字节数组的第一个元素中
String str_12=str_r1+str_r2;
int tempLow=Integer.parseInt(str_12, 16);
bytes[0]=(byte) tempLow;
//将生成的位码保存到字节数组的第二个元素中
String str_34=str_r3+str_r4;
int tempHigh=Integer.parseInt(str_34, 16);
bytes[1]=(byte)tempHigh;
ctmp=new String(bytes);
break;
default:
itmp=random.nextInt(10)+48;
ctmp=String.valueOf((char)itmp);
break;
}
sRand+=ctmp;
Color color=new Color(20+random.nextInt(110),20+random.nextInt(110),random.nextInt(110));
g.setColor(color);
//将生成的随机数进行随机缩放并旋转制定角度 PS.建议不要对文字进行缩放与旋转,因为这样图片可能不正常显示
/*将文字旋转制定角度*/
Graphics2D g2d_word=(Graphics2D)g;
AffineTransform trans=new AffineTransform();
trans.rotate((45)*3.14/180,15*i+8,7);
/*缩放文字*/
float scaleSize=random.nextFloat()+0.8f;
if(scaleSize>1f) scaleSize=1f;
trans.scale(scaleSize, scaleSize);
g2d_word.setTransform(trans);
g.drawString(ctmp, 15*i+18, 14);
}
HttpSession session=request.getSession(true);
session.setAttribute("randCheckCode", sRand);
System.out.println(sRand);
g.dispose(); //释放g所占用的系统资源
ImageIO.write(image,"JPEG",response.getOutputStream()); //输出图片
}
}
2.web.xml配置
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>PictureCheckCode</servlet-name>
<servlet-class>servlet.PictureCheckCode</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>PictureCheckCode</servlet-name>
<url-pattern>/pictureCheckCode</url-pattern>
</servlet-mapping>
3.jsp页面输出验证码
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<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">
<script language="javascript">
function myReload() {
document.getElementById("CreateCheckCode").src = document
.getElementById("CreateCheckCode").src
+ "?nocache=" + new Date().getTime();
}
</script>
</head>
<body>
<form action="loginServlet" method="get">
<p class="font tdheight">
验证码:<input type="text" name="checkCode"
style="width:70px;height:35px;"> <img
src="pictureCheckCode" id="CreateCheckCode" align="middle"
style="margin-top:-10px;"> <br> <a href=""
onclick="myReload()"
style="font-size:12px;color:red;margin-left:156px;"> 看不清,换一个</a>
</p>
<br><input type="submit" value="提交"
class="font" style="width:240px;height:35px;background:#f19e28">
</form>
</body>
</html>
4.后台Servlet判断验证码是否与输入一致
通过request.getParameter(“checkCode”)获取输入验证码,与session.getAttribute(“randCheckCode”)比较是否一致。
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String code = request.getParameter("checkCode");
HttpSession session = request.getSession();
if (!code.equals(session.getAttribute("randCheckCode"))) {
request.setAttribute("errormsg", "验证码不正确");
}
System.out.println(request.getAttribute("errormsg"));
}
运行结果:
来源:http://blog.csdn.net/giving_bestself/article/details/59113140
标签:servlet,验证码
0
投稿
猜你喜欢
python 利用Pyinstaller打包Web项目
2021-11-25 12:22:36
nodejs+mysql实现用户相关的增删改查的详细操作
2024-01-26 10:34:45
使用jQuery向asp.net Mvc传递复杂json数据-ModelBinder篇
2024-06-05 09:32:20
Laravel 4 初级教程之视图、命名空间、路由
2024-06-05 09:23:26
关于程序员生活的一份调查,看看你属于哪一个群体吧
2022-08-11 16:00:48
TensorFlow如何指定GPU训练模型
2022-05-31 10:03:21
PyQt5实现画布小程序
2022-03-02 07:37:46
Python使用list列表和tuple元组的方法
2022-08-10 22:01:49
PHP遍历目录函数opendir()、readdir()、closedir()、rewinddir()总结
2024-05-03 15:53:21
JavaScript求一组数的最小公倍数和最大公约数常用算法详解【面向对象,回归迭代和循环】
2024-05-05 09:13:21
SQL Server游标的介绍与使用
2024-01-21 10:02:25
django 通过URL访问上传的文件方法
2022-09-02 22:03:59
Python中用于去除空格的三个函数的使用小结
2022-02-07 23:43:45
asp源码如何显示数据库字段的结构?
2010-06-08 09:35:00
pycharm新建一个python工程步骤
2023-08-22 17:42:54
python opencv肤色检测的实现示例
2023-06-13 20:31:58
Python cookbook(数据结构与算法)从序列中移除重复项且保持元素间顺序不变的方法
2023-03-01 14:24:38
基于OpenCV(python)的实现文本分割之垂直投影法
2023-11-17 08:45:39
用CSS实现柱状图(Bar Graph)的方法(二)—基于表格元素的柱状图
2008-05-26 13:23:00
Python turtle库绘制菱形的3种方式小结
2022-04-10 14:08:19