原文:http://blog.csdn.net/typa01_kk/article/details/45050091

 /**
* creat verification code
* */
@Action("/getCode")
public void getCode(){
//verification code demander
String vCdemander = request.getParameter("vcdemander");
try{
//set encoding
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
//Verification code tool
VerificationCodeTool vcTool = new VerificationCodeTool();
BufferedImage image = vcTool.drawVerificationCodeImage();
//Verification code result
int vcResult = vcTool.getXyresult();
String vcValue = vcTool.getRandomString();
//Set ban cache
//Cache-control : Specify the request and response following caching mechanism
//no-cache: Indicates a request or response message cannot cache
response.setHeader("Cache-Control", "no-cache");
//Entity header field response expiration date and time are given
response.setHeader("Pragma", "No-cache");
response.setDateHeader("Expires", 0);
// Set the output stream content format as image format
response.setContentType("image/jpeg");
//session
//true: if the session exists, it returns the session, or create a new session.
//false: if the session exists, it returns the session, otherwise it returns null.
session=request.getSession(true);
//set verificationcode to session
//login
if("userlogin".equals(vCdemander)){
session.setAttribute("verificationcodeuserlogin",vcResult);
}
//regiser
if("userregister".equals(vCdemander)){
session.setAttribute("verificationcodeuserregister",vcResult);
}
//To the output stream output image
ImageIO.write(image, "JPEG", response.getOutputStream());
System.out.println("获取验证码成功 :\n验证码:"+vcValue+"\n验证码结果:"+vcResult);
//ResponseUtil.sendImg(response, image, "image/jpeg", "code", "JPEG");
} catch (Exception e) {
System.out.println("获取验证码失败");
}
}
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import org.apache.log4j.Logger; /**
*
*/
public class VerificationCodeTool {
//LOG
private static final Logger LOG =Logger.getLogger(VerificationCodeTool.class);
//verification code image width
private static final int IMG_WIDTH=146;
//verification code image height
private static final int IMG_HEIGHT=30;
//The number of interference lines
private static final int DISTURB_LINE_SIZE = 15;
//generate a random number
private Random random = new Random();
//result
private int xyresult;
//result random string
private String randomString;
//Chinese Numbers
// private static final String [] CNUMBERS = "零,一,二,三,四,五,六,七,八,九,十".split(",");
//零一二三四五六七八九十乘除加减
//Here, must be java Unicode code
private static final String CVCNUMBERS = "\u96F6\u4E00\u4E8C\u4E09\u56DB\u4E94\u516D\u4E03\u516B\u4E5D\u5341\u4E58\u9664\u52A0\u51CF";
//Definition of drawings in the captcha characters font, font name, font style, font size
//static final font : In Chinese characters garbled
private final Font font = new Font("黑体", Font.BOLD, 18);
//data operator
private static final Map<String, Integer> OPMap = new HashMap<String, Integer>(); static{
OPMap.put("*", 11);
OPMap.put("/", 12);
OPMap.put("+", 13);
OPMap.put("-", 14);
}
/**
* The generation of image verification code
* */
public BufferedImage drawVerificationCodeImage(){
//image
BufferedImage image = new BufferedImage(IMG_WIDTH, IMG_HEIGHT, BufferedImage.TYPE_INT_RGB);
//In memory to create a brush
Graphics g = image.getGraphics();
//Set the brush color
// g.setColor(getRandomColor(200,250));
g.setColor(Color.WHITE);
//Fill the background color, using the current brush colour changing background color images
//The meaning of the four parameters respectively, starting x coordinates, starting y, width, height.
//image background
g.fillRect(0, 0, IMG_WIDTH, IMG_HEIGHT);
//Set the brush color
g.setColor(getRandomColor(200,250));
//image border
g.drawRect(0, 0, IMG_WIDTH-2, IMG_HEIGHT-2); //Set disturb line color
g.setColor(getRandomColor(110, 133));
//Generate random interference lines
for(int i =0;i < DISTURB_LINE_SIZE; i++){
drawDisturbLine1(g);
drawDisturbLine2(g);
}
//Generate a random number, set return data
getRandomMathString();
LOG.info("验证码 : "+randomString);
LOG.info("验证码结果 : "+xyresult);
//The generated random string used to save the system
StringBuffer logsu = new StringBuffer();
for(int j=0,k = randomString.length(); j < k; j++){
int chid = 0;
if(j==1){
chid = OPMap.get(String.valueOf(randomString.charAt(j)));
}else{
chid = Integer.parseInt(String.valueOf(randomString.charAt(j)));
}
String ch = String.valueOf(CVCNUMBERS.charAt(chid));
logsu.append(ch);
drawRandomString((Graphics2D)g,ch, j);
}
//= ?
drawRandomString((Graphics2D)g,"\u7B49\u4E8E\uFF1F", 3);
logsu.append("\u7B49\u4E8E \uFF1F");
LOG.info("汉字验证码 : "+logsu);
randomString = logsu.toString();
//Release the brush object
g.dispose();
return image;
}
/**
* Get a random string
* */
private void getRandomMathString(){
//Randomly generated number 0 to 10
int xx = random.nextInt(10);
int yy = random.nextInt(10);
//save getRandomString
StringBuilder suChinese = new StringBuilder();
//random 0,1,2
int Randomoperands = (int) Math.round(Math.random()*2);
//multiplication
if(Randomoperands ==0){
this.xyresult = yy * xx;
// suChinese.append(CNUMBERS[yy]);
suChinese.append(yy);
suChinese.append("*");
suChinese.append(xx);
//division, divisor cannot be zero, Be divisible
}else if(Randomoperands ==1){
if(!(xx==0) && yy%xx ==0){
this.xyresult = yy/xx;
suChinese.append(yy);
suChinese.append("/");
suChinese.append(xx);
}else{
this.xyresult = yy + xx;
suChinese.append(yy);
suChinese.append("+");
suChinese.append(xx);
}
//subtraction
}else if(Randomoperands ==2){
this.xyresult = yy - xx;
suChinese.append(yy);
suChinese.append("-");
suChinese.append(xx);
//add
}else{
this.xyresult = yy + xx;
suChinese.append(yy);
suChinese.append("+");
suChinese.append(xx);
}
this.randomString = suChinese.toString();
}
/**
* Draw a random string
* @param g Graphics
* @param randomString random string
* @param i the random number of characters
* */
public void drawRandomString(Graphics2D g,String randomvcch,int i){
//Set the string font style
g.setFont(font);
//Set the color string
int rc = random.nextInt(255);
int gc = random.nextInt(255);
int bc = random.nextInt(255);
g.setColor(new Color(rc, gc, bc));
//random string
//Set picture in the picture of the text on the x, y coordinates, random offset value
int x = random.nextInt(3);
int y = random.nextInt(2);
g.translate(x, y);
//Set the font rotation angle
int degree = new Random().nextInt() % 15;
//Positive point of view
g.rotate(degree * Math.PI / 180, 5+i*25, 20);
//Character spacing is set to 15 px
//Using the graphics context of the current font and color rendering by the specified string for a given text.
//The most on the left side of the baseline of the characters in the coordinate system of the graphics context (x, y) location
//str- to draw string.x - x coordinate.y - y coordinate.
g.drawString(randomvcch, 5+i*25, 20);
//Reverse Angle
g.rotate(-degree * Math.PI / 180, 5+i*25, 20);
}
/**
*Draw line interference
*@param g Graphics
* */
public void drawDisturbLine1(Graphics g){
int x1 = random.nextInt(IMG_WIDTH);
int y1 = random.nextInt(IMG_HEIGHT);
int x2 = random.nextInt(13);
int y2 = random.nextInt(15);
//x1 - The first point of the x coordinate.
//y1 - The first point of the y coordinate
//x2 - The second point of the x coordinate.
//y2 - The second point of the y coordinate.
//X1 and x2 is the starting point coordinates, x2 and y2 is end coordinates.
g.drawLine(x1, y1, x1 + x2, y1 + y2);
} /**
*Draw line interference
*@param g Graphics
* */
public void drawDisturbLine2(Graphics g){
int x1 = random.nextInt(IMG_WIDTH);
int y1 = random.nextInt(IMG_HEIGHT);
int x2 = random.nextInt(13);
int y2 = random.nextInt(15);
//x1 - The first point of the x coordinate.
//y1 - The first point of the y coordinate
//x2 - The second point of the x coordinate.
//y2 - The second point of the y coordinate.
//X1 and x2 is the starting point coordinates, x2 and y2 is end coordinates.
g.drawLine(x1, y1, x1 - x2, y1 - y2);
}
/**
* For random color
* @param fc fc
* @param bc bc
* @return color random color
* */
public Color getRandomColor(int fc,int bc){
if(fc > 255){
fc = 255;
}
if(bc > 255){
bc = 255;
}
//Generate random RGB trichromatic
int r = fc+random.nextInt(bc -fc - 16);
int g = fc+random.nextInt(bc - fc - 14);
int b = fc+random.nextInt(bc - fc - 18);
return new Color(r, g, b);
} /**
* xyresult.<br/>
*
* @return the xyresult <br/>
*
*/
public int getXyresult() {
return xyresult;
} /**
* randomString.<br/>
*
* @return the randomString <br/>
*
*/
public String getRandomString() {
return randomString;
} }

Java实现中文算数验证码(算数运算+-*/)的更多相关文章

  1. 11大Java开源中文分词器的使用方法和分词效果对比,当前几个主要的Lucene中文分词器的比较

    本文的目标有两个: 1.学会使用11大Java开源中文分词器 2.对比分析11大Java开源中文分词器的分词效果 本文给出了11大Java开源中文分词的使用方法以及分词结果对比代码,至于效果哪个好,那 ...

  2. 11大Java开源中文分词器的使用方法和分词效果对比

    本文的目标有两个: 1.学会使用11大Java开源中文分词器 2.对比分析11大Java开源中文分词器的分词效果 本文给出了11大Java开源中文分词的使用方法以及分词结果对比代码,至于效果哪个好,那 ...

  3. java去中文

    java 去中文 package a.b; public class TrimCNTool { public static boolean checkCNChar(char oneChar) { if ...

  4. java ee 中文乱码的问题

    java ee 中文乱码的问题 发生中文乱码的三种情况 (一) 表单form Post 方法 直接在服务器中设置 request.setCharacterEncoding("utf-8&qu ...

  5. AndroidStudio开发Java工程(解决java控制台中文打印乱码+导入jar包运行工程)

    这篇分享一点个人AS开发java工程经验,虽然有时候还是得打开eclipse来运行java项目,但能用AS的时候还是尽量用AS,毕竟一个字,爽~ 废话不多说,进入正题. 一.开发Java工程 你有两种 ...

  6. 用java实现邮件发送验证码

    java实现邮件发送验证码 建议不要用qq邮箱,我使用qq邮箱直接一直给我报530错误,我一直认为我代码写的有错误或者POP3/SMTP服务没弄好.所以建议注册个别的邮箱,我就申请了个网易163邮箱瞬 ...

  7. java使用DateUtils对日期进行运算

    最近在写数据上传的程序,需要对Date进行一些数学运算,个人感觉在java中,日期的数学运算还是比较常用的,所以把Date的数学运算都玩了一下.试了一下,发现DateUtils这个工具类对于Date的 ...

  8. 推荐十款java开源中文分词组件

    1:Elasticsearch的开源中文分词器 IK Analysis(Star:2471) IK中文分词器在Elasticsearch上的使用.原生IK中文分词是从文件系统中读取词典,es-ik本身 ...

  9. JAVA的中文字符乱码问题

    来源:http://luzefengoo.blog.163.com/blog/static/1403593882012754428536/ JAVA的中文字符乱码问题一直很让人头疼.特别是在WEB应用 ...

随机推荐

  1. TZOJ3043: 取个标题好难 最长的出现次数>=k的不重复子串长度

    3043: 取个标题好难  Time Limit(Common/Java):6000MS/18000MS     Memory Limit:65536KByteTotal Submit: 17     ...

  2. 波动数列 神奇的dp

    问题描述 观察这个数列: 1 3 0 2 -1 1 -2 ... 这个数列中后一项总是比前一项增加2或者减少3. 栋栋对这种数列很好奇,他想知道长度为 n 和为 s 而且后一项总是比前一项增加a或者减 ...

  3. 分享下自己一直用的.NET SQLSERVER 封装类下自己写的DataHelper 操作类

    一,概述: 这个DataHelper 类是基于我上个博客里发的SQLDataAccess 这个类做的一个简单的封装,为了结合自己的实体类和数据操作而产生的. 这里面用了  属性类,反射.还有 数据类型 ...

  4. 在浏览器中进行深度学习:TensorFlow.js (八)生成对抗网络 (GAN

    Generative Adversarial Network 是深度学习中非常有趣的一种方法.GAN最早源自Ian Goodfellow的这篇论文.LeCun对GAN给出了极高的评价: “There ...

  5. POJ3252 Round Numbers 【数位dp】

    题目链接 POJ3252 题解 为什么每次写出数位dp都如此兴奋? 因为数位dp太苟了 因为我太弱了 设\(f[i][0|1][cnt1][cnt0]\)表示到二进制第\(i\)位,之前是否达到上界, ...

  6. 洛谷 P2041 分裂游戏 解题报告

    P2041 分裂游戏 题目描述 有一个无限大的棋盘,棋盘左下角有一个大小为 n 的阶梯形区域,其中最左下角的那个格子里有一枚棋子.你每次可以把一枚棋子"分裂"成两枚棋子,分别放在原 ...

  7. 2016华中农业大学预赛 B 数学

    Problem B: Handing Out Candies Time Limit: 1 Sec  Memory Limit: 128 MBSubmit: 272  Solved: 20[Submit ...

  8. 7月13号day5总结

    今天学习过程和小结 使用伪分布式进行大数据计算,计算气象站记录气温的平均值 weather map()方法,key值数据多所以用LongWritable,value值是string类型,string类 ...

  9. Gradle for Android(二)全局设置、自定义BuildConfig

    全局设置 如果有很多项目,可以设置全局来统一管理版本号或依赖库,根目录下build.gradle下: ext { compileSdkVersion = 23 buildToolsVersion = ...

  10. 杭电oj2022-2030

    2022 海选女主角 #include <stdio.h> #include <math.h> int main(){ ][]; int n,m,x,y,z,i,j; whil ...