中文验证码
chineseRandomCode.jsp
pageEncoding="UTF-8"%>
//生成随机颜色
Color getRandColor(Random random, int fc, int bc) {
if (fc > 255) {
fc = 255;
}
if (bc > 255) {
bc = 255;
}
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
}
%>
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "No-cache");
response.setDateHeader("Expires", 0);
//设置图片的长宽
int width = 100;
int height = 25;
String base = "去年月日国务院关于机关事业单位工作人员养老保险制度改革的决定公布起实施近四千万机关事业单位人员开始缴纳基本养老保险同时其基本工资也进行了调整截至底机关事业单位调整基本工资标准的兑现工作全面完成此次工资调整优化了工资结构将部分规范津贴补贴或绩效工资纳入基本工资提高了基本工资占工资的比重同时重点向基层倾斜并确保所有人员的工资都有所增加按全国平均水平计算月人均实际增资为元左右需要指出的是去年人社部有关负责人就机关事业单位调资工作答记者问时曾指出这次调资工作进一步明确了建立基本工资标准正常调整机制近期要每两年调整一次基本工资标准对于如何调人社部表示将依据工资调查比较结综合考虑国民经济发展财政状况和物价变动等因素确定调整幅度逐步提高基本工资占工资的比重";
int length = base.length();
//创建图像
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//获取图像
Graphics g = image.getGraphics();
//创建随机类的实例
Random random = new Random();
//设轩图像背景色
g.setColor(getRandColor(random, 200, 250));
g.fillRect(0, 0, width, height);
//设轩备选字体
String[] fontTypes = {"宋体", "微软雅黑", "楷体", "新宋体"};
int fontTypesLength = fontTypes.length;
//在图像上增加干扰点
g.setColor(getRandColor(random, 160, 200));
g.setFont(new Font("Times New Roman", Font.PLAIN, 14));
for (int i = 0; i < 4; i++) {
g.drawString("************************", 0, 5 * (i + 2));
}
//图像显示验证码
String sRand = "";
for (int i = 0; i < 4; i++) {
int start = random.nextInt(length);
String rand = base.substring(start, start + 1);
sRand += rand;
g.setColor(getRandColor(random, 10, 150));
g.setFont(new Font(fontTypes[random.nextInt(fontTypesLength)], Font.BOLD, 12 + random.nextInt(6)));
g.drawString(rand, 20 * i + random.nextInt(8), 20);
}
//验证码存入session
g.dispose();
ImageIO.write(image, "JPEG", response.getOutputStream());
out.clear();
out=pageContext.popBody();
%>
运行结果如下:
code.jsp:
import="java.awt.*"
import="java.awt.image.BufferedImage"
import="java.util.*"
import="javax.imageio.ImageIO"
pageEncoding="utf-8" %>
response.setHeader("Cache-Control", "no-cache");
//create image in RAM!
int width=60,height=20;
BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
//get graphics
Graphics g=image.getGraphics();
g.setColor(new Color(200,200,200));
g.fillRect(0, 0, width, height);
//create randrom (4 namber)
Random rnd = new Random();
int randNum=rnd.nextInt(8999)+1000;
String randStr=String.valueOf(randNum);
//save in session
session.setAttribute("randStr", randStr);
//display to image
g.setColor(Color.black);
g.setFont(new Font("",Font.PLAIN,20));
g.drawString(randStr, 10, 17);
//100-other
//
//output image to page
ImageIO.write(image, "JPEG", response.getOutputStream());
out.clear();
out=pageContext.popBody();
%>
运行结果如下: