这几天在登录一些网站和应用的时候,发现验证码不是以前那种简单的字母加数字的验证码,
而是变成了各种各样的汉字验证码,之后找了相关资料,自己实现了一下,分享给大家。
1、运行后的结果
2、创建web项目,新建一个servlet类
下一步,
3、页面代码
package com.yuyu;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
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 ChineseCheckCode extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");//使客户端浏览器,区分不同种类的数据
response.setContentType("image/jpeg");
response.setHeader("Cache-Control", "no-cache");//response.setHeader 是用来设置返回页面的头信息
response.setHeader("Pragma", "no-cache");
int width = 166;//设置图片高度和宽度
int height = 80;
//图像
BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_BGR);//TYPE_INT_BGR:表示一个具有 8 位 RGB 颜色分量的图像
Graphics g = image.getGraphics();
Random random = new Random();
Font myFont = new Font("楷体",Font.ITALIC,26);//Font.ITALIC 斜体
g.fillRect(0, 0, width, height);
g.setFont(myFont);
String sRand = "";
String ctmp = "";
@SuppressWarnings("unused")
String itmp = "";
for(int i=0;i<4;i++){//循环4次,生成4个中文字符
String[] rBase = {"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"};//16进制
int r1 = random.nextInt(3)+11;//返回一个11~14的值
String str_r1 = rBase[r1];
int r2;
if(r1==13){
r2 = random.nextInt(7); //0~7
}
else{
r2 = random.nextInt(16);//0~16
}
String str_r2 = rBase[r2];
int r3 = random.nextInt(6)+10;//10~16
String str_r3 = rBase[r3];
int r4;
if(r3==10){
r4=random.nextInt(15)+1;//1~16
}
else if(r3==15){
r4= random.nextInt(15);
}
else{
r4=random.nextInt(16);
}
String str_r4 = rBase[r4];
byte[] bytes = new byte[2];
String r12 = str_r1+str_r2;
int tempLow = Integer.parseInt(r12,16);//解析一个字符串,并返回一个整数,按照16进制
bytes[0] = (byte)tempLow;
String r34 = str_r3 + str_r4;
int tempHeight = Integer.parseInt(r34, 16);
bytes[1]=(byte)tempHeight;
ctmp=new String(bytes);
sRand+=ctmp;
Color color = new Color(20+random.nextInt(110));
g.setColor(color);
g.drawString(ctmp, width/6*i+23, height/3);
}
HttpSession session = request.getSession(true);
session.setAttribute("randCheckCode", sRand);
g.dispose();
ImageIO.write(image, "JPEG", response.getOutputStream());//存储格式图片
}
}
4、发布运行
在浏览器输入框中输入:http://localhost:7001/CheckCode/ChineseCheckCode
(PS:如果不删除前面的那个servlet,输入的时候记得在CheckCode前加上)
这样就完成了。