导航:首页 > 编程语言 > java写验证码

java写验证码

发布时间:2022-09-24 16:42:49

1. 验证码部分的java代码怎么写

package com.bbs.servlet;

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.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 com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class Image extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("image/jpeg");
OutputStream out = response.getOutputStream();
response.setHeader("Pragma","No-cache");
response.setHeader("Cache-Control","no-cache");
response.setDateHeader("Expires", 0);
int width = 60, height = 20;
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
// 获取图形上下文
Graphics g = image.getGraphics();
// 生成随机类
Random random = new Random();
// 设定背景色
g.setColor(getRandColor(200, 250));
g.fillRect(0, 0, width, height);
// 设定字体
g.setFont(new Font("Times New Roman", Font.PLAIN, 18));
// 随机产生155条干扰线,使图象中的认证码不易被其它程序探测到
g.setColor(getRandColor(180, 200));
for (int i = 0; i < 155; i++) {
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(12);
int yl = random.nextInt(12);
g.drawLine(x, y, x + xl, y + yl);
}
// 取随机产生的认证码(4位数字)
String sRand =setRandValue(request);
if(sRand!=null)
for (int i = 0; i < sRand.length(); i++) {
g.setColor(new Color(20 + random.nextInt(200), 20 + random
.nextInt(200), 20 + random.nextInt(200)));
// 调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成
g.drawString(sRand.charAt(i) + "", 13 * i + 6, 16);
}

JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(image);
// 图象生效
g.dispose();
// 输出图象到页面
// ImageIO.write(image, "JPG", response.getOutputStream());
out.flush();
out.close();
}

Color getRandColor(int fc, int bc) {// 给定范围获得随机颜色
Random random = new Random();
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);
}
//48-57对应0-9;65-90对应A-Z;97-122对应a-z;
String setRandValue(HttpServletRequest request) {
Random random = new Random();
String sRand = "";
//这里是生成验证码的位数
for (int i = 0; i < 4; i++) {
char c = 0;
int k = random.nextInt(3);
switch (k) {
case 0:
c = (char) (random.nextInt(10) + 48);
break;
case 1:
c = (char) (random.nextInt(26) + 65);
break;
case 2:
c = (char) (random.nextInt(26) + 97);
}
sRand += c;
}
request.getSession().setAttribute("rands", sRand);
return sRand;
}
}

2. java如何实现发送短信验证码功能

1、创建一个Http的模拟请求工具类,然后写一个POST方法或者GET方法

/** * 文件说明 * @Description:扩展说明 * @Copyright: XXXX dreamtech.com.cn Inc. All right reserved * @Version: V6.0 */package com.demo.util; import java.io.IOException;import java.util.Map; import org.apache.commons.httpclient.HttpClient;import org.apache.commons.httpclient.HttpException;import org.apache.commons.httpclient.SimpleHttpConnectionManager;import org.apache.commons.httpclient.methods.GetMethod;import org.apache.commons.httpclient.methods.PostMethod; /** * @Author: feizi * @Date: XXXX年XX月XX日 XX:XX:XX * @ModifyUser: feizi * @ModifyDate: XXXX年XX月XX日 XX:XX:XX * @Version:V6.0 */public class HttpRequestUtil { /** * HttpClient 模拟POST请求 * 方法说明 * @Discription:扩展说明 * @param url * @param params * @return String * @Author: feizi * @Date: XXXX年XX月XX日 XX:XX:XX * @ModifyUser:feizi * @ModifyDate: XXXX年XX月XX日 XX:XX:XX */ public static String postRequest(String url, Map<String, String> params) { //构造HttpClient的实例 HttpClient httpClient = new HttpClient(); //创建POST方法的实例 PostMethod postMethod = new PostMethod(url); //设置请求头信息 postMethod.setRequestHeader("Connection", "close"); //添加参数 for (Map.Entry<String, String> entry : params.entrySet()) { postMethod.addParameter(entry.getKey(), entry.getValue()); } //使用系统提供的默认的恢复策略,设置请求重试处理,用的是默认的重试处理:请求三次 httpClient.getParams().setBooleanParameter("http.protocol.expect-continue", false); //接收处理结果 String result = null; try { //执行Http Post请求 httpClient.executeMethod(postMethod); //返回处理结果 result = postMethod.getResponseBodyAsString(); } catch (HttpException e) { // 发生致命的异常,可能是协议不对或者返回的内容有问题 System.out.println("请检查输入的URL!"); e.printStackTrace(); } catch (IOException e) { // 发生网络异常 System.out.println("发生网络异常!"); e.printStackTrace(); } finally { //释放链接 postMethod.releaseConnection(); //关闭HttpClient实例 if (httpClient != null) { ((SimpleHttpConnectionManager) httpClient.getHttpConnectionManager()).shutdown(); httpClient = null; } } return result; } /** * HttpClient 模拟GET请求 * 方法说明 * @Discription:扩展说明 * @param url * @param params * @return String * @Author: feizi * @Date: XXXX年XX月XX日 XX:XX:XX * @ModifyUser:feizi * @ModifyDate: XXXX年XX月XX日 XX:XX:XX */ public static String getRequest(String url, Map<String, String> params) { //构造HttpClient实例 HttpClient client = new HttpClient(); //拼接参数 String paramStr = ""; for (String key : params.keySet()) { paramStr = paramStr + "&" + key + "=" + params.get(key); } paramStr = paramStr.substring(1); //创建GET方法的实例 GetMethod method = new GetMethod(url + "?" + paramStr); //接收返回结果 String result = null; try { //执行HTTP GET方法请求 client.executeMethod(method); //返回处理结果 result = method.getResponseBodyAsString(); } catch (HttpException e) { // 发生致命的异常,可能是协议不对或者返回的内容有问题 System.out.println("请检查输入的URL!"); e.printStackTrace(); } catch (IOException e) { // 发生网络异常 System.out.println("发生网络异常!"); e.printStackTrace(); } finally { //释放链接 method.releaseConnection(); //关闭HttpClient实例 if (client != null) { ((SimpleHttpConnectionManager) client.getHttpConnectionManager()).shutdown(); client = null; } } return result; }}

2、在创建一个类,生成验证码,然后传递相应的参数(不同的短信平台接口会有不同的参数要求,这个一般短信平台提供的接口文档中都会有的,直接看文档然后按要求来即可)

/** * 文件说明 * @Description:扩展说明 * @Copyright: XXXX dreamtech.com.cn Inc. All right reserved * @Version: V6.0 */package com.demo.util; import java.net.URLEncoder;import java.util.HashMap;import java.util.Map; /** * @Author: feizi * @Date: XXXX年XX月XX日 XX:XX:XX * @ModifyUser: feizi * @ModifyDate: XXXX年XX月XX日 XX:XX:XX * @Version:V6.0 */public class SendMsgUtil { /** * 发送短信消息 * 方法说明 * @Discription:扩展说明 * @param phones * @param content * @return * @return String * @Author: feizi * @Date: 2015年4月17日 下午7:18:08 * @ModifyUser:feizi * @ModifyDate: 2015年4月17日 下午7:18:08 */ @SuppressWarnings("deprecation") public static String sendMsg(String phones,String content){ //短信接口URL提交地址 String url = "短信接口URL提交地址"; Map<String, String> params = new HashMap<String, String>(); params.put("zh", "用户账号"); params.put("mm", "用户密码"); params.put("dxlbid", "短信类别编号"); params.put("extno", "扩展编号"); //手机号码,多个号码使用英文逗号进行分割 params.put("hm", phones); //将短信内容进行URLEncoder编码 params.put("nr", URLEncoder.encode(content)); return HttpRequestUtil.getRequest(url, params); } /** * 随机生成6位随机验证码 * 方法说明 * @Discription:扩展说明 * @return * @return String * @Author: feizi * @Date: 2015年4月17日 下午7:19:02 * @ModifyUser:feizi * @ModifyDate: 2015年4月17日 下午7:19:02 */ public static String createRandomVcode(){ //验证码 String vcode = ""; for (int i = 0; i < 6; i++) { vcode = vcode + (int)(Math.random() * 9); } return vcode; } /** * 测试 * 方法说明 * @Discription:扩展说明 * @param args * @return void * @Author: feizi * @Date: XXXX年XX月XX日 XX:XX:XX * @ModifyUser:feizi * @ModifyDate: XXXX年XX月XX日 XX:XX:XX */ public static void main(String[] args) {// System.out.println(SendMsgUtil.createRandomVcode());// System.out.println("&ecb=12".substring(1)); System.out.println(sendMsg("18123456789,15123456789", "尊敬的用户,您的验证码为" + SendMsgUtil.createRandomVcode() + ",有效期为60秒,如有疑虑请详询XXX-XXX-XXXX【XXX中心】")); }

然后执行一下,一般的情况下参数传递正确,按照接口文档的规范来操作的话,都会发送成功的,手机都能收到验证码的,然后可能会出现的问题就是:发送的短信内容有可能会出现中文乱码,然后就会发送不成功,按照短信平台的要求进行相应的编码即可。一般都会是UTF-8编码。

3. java 登陆时的验证码怎么做

后台写一个生成图片随机的代码,生成图片给前台。切换图片的时候,使用ajax获取图片数据就行。
附上生成图片的代码
public class ValidateCode {

private int width=180;
private int height=60;
private int codeCount = 4;
private int x = 0;
private int codeY;
private String Code;
private BufferedImage buffImg;
static char[] codeSequence = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
'X', 'Y', 'Z','a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
'x', 'y', 'z', 'o', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
private int fontHeight;

public ValidateCode() {
x = width / (codeCount + 2);
fontHeight = height - 2;
codeY = height - 4;
CreateCode();
}

public void CreateCode(){

// 定义图像buffer
BufferedImage buffImg = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);
Graphics2D g = buffImg.createGraphics();
// 创建一个随机数生成器类
Random random = new Random();

// 将图像填充为白色
g.setColor(Color.WHITE);
g.fillRect(0, 0, width, height);

// 创建字体,字体的大小应该根据图片的高度来定。
Font font = new Font("Fixedsys", Font.PLAIN, fontHeight);
// 设置字体。
g.setFont(font);

// 画边框。
g.setColor(Color.BLACK);
g.drawRect(0, 0, width - 1, height - 1);

// randomCode用于保存随机产生的验证码,以便用户登录后进行验证。
StringBuffer randomCode = new StringBuffer();
int red = 0, green = 0, blue = 0;

// 随机产生codeCount数字的验证码。
for (int i = 0; i < codeCount; i++) {
// 得到随机产生的验证码数字。
String strRand = String.valueOf(codeSequence[random.nextInt(62)]);
// 产生随机的颜色分量来构造颜色值,这样输出的每位数字的颜色值都将不同。
red = random.nextInt(255);
green = random.nextInt(255);
blue = random.nextInt(255);

// 用随机产生的颜色将验证码绘制到图像中。
g.setColor(new Color(red, green, blue));
g.drawString(strRand, (i ) * x+20, codeY);

// 将产生的四个随机数组合在一起。
randomCode.append(strRand);
}
this.Code=randomCode.toString().toUpperCase();
this.buffImg=buffImg;

}

public String getCode() {
return Code;
}

public void setCode(String code) {
Code = code;
}

public BufferedImage getBuffImg() {
return buffImg;
}

public void setBuffImg(BufferedImage buffImg) {
this.buffImg = buffImg;
}
}

4. java怎么编写混合验证码(控制台输出就可以)



importjava.util.Random;


{
//验证码图片中可以出现的字符集,可以根据需要修改
privatestaticcharmapTable[]={
'a','b','c','d','e','f',
'g','h','i','j','k','l',
'm','n','o','p','q','r',
's','t','u','v','w','x',
'y','z','0','1','2','3',
'4','5','6','7','8','9'
};

staticRandomsc=newRandom();

publicstaticvoidmain(String[]args)
{
System.out.println("混合验证码:");
for(inti=0;i<4;i++)
{
System.out.print(mapTable[sc.nextInt(mapTable.length)]);
}
}
}

5. java 登录验证码代码怎么写

原理: 1.随机生成4个数字 用到了Random类 2.对这4个数字设置字体格式 用 setFont方法 3.改变字体颜色用setColor 然后随机生成颜色 代码如下 package s1; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.a

6. spring框架的java登录验证码怎么写

可以参考下下面的代码,这个代码是servlet生成的,稍微修改下就能用的

packageservlet;

importjava.awt.Color;
importjava.awt.Font;
importjava.awt.Graphics;
importjava.awt.image.BufferedImage;
importjava.io.IOException;
importjava.io.OutputStream;
importjava.util.Random;

importjavax.imageio.ImageIO;
importjavax.servlet.ServletException;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importjavax.servlet.http.HttpSession;

{

publicvoidservice(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException{

BufferedImageimage=newBufferedImage(100,30,BufferedImage.TYPE_INT_RGB);
Graphicsg=image.getGraphics();
Randomr=newRandom();
g.setColor(newColor(r.nextInt(255),r.nextInt(255),r.nextInt(255)));
g.fillRect(0,0,100,30);
g.setColor(newColor(255,255,255));
g.setFont(newFont(null,Font.BOLD,24));
Stringcode=getCode();
HttpSessionsession=request.getSession();
session.setAttribute("textcode",code);

g.drawString(code,10,25);
response.setContentType("image/jpeg");
OutputStreamos=response.getOutputStream();
ImageIO.write(image,"jpeg",os);
os.close();
}
//随机生成验证码字符串的类
publicstaticStringgetCode(){
char[]letters={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t',
'u','v','w','x','y','z'};
Stringcode="";
boolean[]bool=newboolean[letters.length];

for(inti=0;i<5;i++){
intnum;
do{
num=(int)(Math.random()*(letters.length));
}while(bool[num]);
code+=letters[num];
bool[num]=true;
}
returncode.toUpperCase();
}

}

7. 怎样用java实现验证码

package com.servlet;

import java.awt.*;
import java.awt.geom.*;
import java.awt.image.*;
import java.io.*;
import java.util.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.imageio.ImageIO;

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);
}

@Override
public void service(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=86,height=22; //指定生成验证码的宽度和高度
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);
g.dispose(); //释放g所占用的系统资源
ImageIO.write(image,"JPEG",response.getOutputStream()); //输出图片
}
}

8. 如何用Java代码段生成四位数字加字母的验证码

不知道你问的是不是生成这种图片验证码?如果只要一个随机四位数 那这行代码就够了(new Random().nextInt(9000) + 1000;),如果是生成页面图片验证码就是下面的了: //设定 响应模式 resp.setContentType("image/jpeg"); // 生成令牌环数据; Integer token = new Random().nextInt(9000) + 1000; // 保存令牌环数据到session中 req.getSession().setAttribute(IMAGE_TOKEN_NAME, token); // 生成令牌环图片 ServletOutputStream out = resp.getOutputStream(); BufferedImage img = new BufferedImage(60, 20, BufferedImage.TYPE_INT_RGB); Graphics g = img.getGraphics(); g.setColor(Color.YELLOW); g.fillRect(0, 0, img.getWidth(), img.getHeight()); g.setColor(Color.BLUE); g.setFont(new Font("", Font.BOLD, 18)); g.drawString(String.valueOf(token), 10, 16); ImageIO.write(img, "jpg", out); out.close();
下面简单的介绍他们的功能和用途,执行效率等。每个都有各自的优缺点看你是做甚什么方面的研究开发用。.net,是网站编程,现在很多都用这个,但是这个语言编程都有统一思路,很好掌握。窒息那个效率不是很高;php 支持跨平台,很容易学会,执行的效率很高;asp是ASP.net的前身,它比较稳定,比.net要弱一点。但是比.net好学。jsp 是网页编程,这个学习大约一周就能搞定,不过这个得多实践,不然的话,时间长了,就容易忘记。
我自己做的系统里面用作验证码的JSP的<%@page contentType="image/jpeg;charset=utf-8"%><%@page import="java.util.*,java.awt.*,java.awt.image.*,javax.imageio.*" %><%@ page import="java.io.OutputStream" %><html> <body> <%! Color getRandColor(int fc,int bc) { Random rd=new Random(); if(fc>255) fc=255; if(bc>255) bc=255; int red=fc+rd.nextInt(bc-fc); int green=fc+rd.nextInt(bc-fc); int blue=fc+rd.nextInt(bc-fc); return new Color(red,green,blue); } %> <% Random r=new Random(); response.addHeader("Pragma","No-cache"); response.addHeader("Cache-Control","no-cache"); response.addDateHeader("expires",0); int width=90; int height=23; BufferedImage pic=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB); Graphics gc=pic.getGraphics(); gc.setColor(getRandColor(200,250)); gc.fillRect(0,0,width,height); String[] rNum ={"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f", "g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w", "x","y","z","A","B","C","D","E","F","G","H","I","J","K","L","M","N", "O","P","Q","R","S","T","U","V","W","X","Y","Z"}; int[] style = {Font.PLAIN,Font.BOLD,Font.ITALIC,Font.PLAIN+Font.BOLD, Font.BOLD+Font.ITALIC,Font.PLAIN+Font.ITALIC,Font.PLAIN+Font.BOLD+Font.ITALIC}; gc.setColor(Color.WHITE); gc.drawLine(0,30,90,10); gc.setColor(getRandColor(160,200)); for (int i=0;i<50;i++) { int x = r.nextInt(width); int y = r.nextInt(height); int xl = r.nextInt(10); int yl = r.nextInt(10); gc.drawLine(x,y,x+xl,y+yl); } gc.setColor(getRandColor(60,150)); String rt = ""; for(int i=0;i<4;i++){ String temp = rNum[r.nextInt(62)]; rt = rt+temp; gc.setFont(new Font("Times New Roman",style[r.nextInt(7)],15)); gc.drawString(temp,5+i*15+r.nextInt(10),10+r.nextInt(10)); } gc.dispose(); session.setAttribute("randNum",rt); OutputStream os=response.getOutputStream(); ImageIO.write(pic,"JPEG",os); System.out.println("当前验证码为:"+session.getAttribute("randNum")); os.flush(); os.close(); os=null; response.flushBuffer(); out.clear(); out = pageContext.pushBody(); %> </body></html>

9. 如何在java中生成验证码在页面生成

以下是我写的生成的图片验证码

//调用验证码生成并把验证码返回页面
Map<String,BufferedImage>imageMap=ImageUtil.createImage();
Stringcode=imageMap.keySet().iterator().next();
session.setAttribute("imageCode",code);
BufferedImageimage=imageMap.get(code);
response.setContentType("image/jpeg");
OutputStreamops=response.getOutputStream();
ImageIO.write(image,"jpeg",ops);
ops.close();
//生成验证码工具类
publicfinalclassImageUtil{

privatestaticfinalchar[]chars={'A','B','C','D','E','F','G','H','I','J',
'K','L','M','N','O','P','Q','R','S','T','U','V','W',
'X','Y','Z','0','1','2','3','4','5','6','7','8','9'};
privatestaticfinalintSIZE=4;
privatestaticfinalintLINES=5;
privatestaticfinalintWIDTH=80;
privatestaticfinalintHEIGHT=40;
privatestaticfinalintFONT_SIZE=30;

publicstaticMap<String,BufferedImage>createImage(){
StringBuffersb=newStringBuffer();
BufferedImageimage=newBufferedImage(WIDTH,HEIGHT,
BufferedImage.TYPE_INT_RGB);
Graphicsgraphic=image.getGraphics();
graphic.setColor(Color.LIGHT_GRAY);
graphic.fillRect(0,0,WIDTH,HEIGHT);
Randomran=newRandom();
//画随机字符
for(inti=1;i<=SIZE;i++){
intr=ran.nextInt(chars.length);
graphic.setColor(getRandomColor());
graphic.setFont(newFont(null,Font.BOLD+Font.ITALIC,FONT_SIZE));
graphic.drawString(chars[r]+"",(i-1)*WIDTH/SIZE,HEIGHT/2);
sb.append(chars[r]);
}
//画干扰线
for(inti=1;i<=LINES;i++){
graphic.setColor(getRandomColor());
graphic.drawLine(ran.nextInt(WIDTH),ran.nextInt(HEIGHT),
ran.nextInt(WIDTH),ran.nextInt(HEIGHT));
}
Map<String,BufferedImage>map=newHashMap<String,BufferedImage>();
map.put(sb.toString(),image);
returnmap;
}

(){
Randomran=newRandom();
Colorcolor=newColor(ran.nextInt(256),ran.nextInt(256),ran.nextInt(256));
returncolor;
}

(BufferedImageimage)
throwsIOException{
ByteArrayOutputStreambos=newByteArrayOutputStream();
JPEGImageEncoderencoder=JPEGCodec.createJPEGEncoder(bos);
encoder.encode(image);
byte[]imageBts=bos.toByteArray();
InputStreamin=newByteArrayInputStream(imageBts);
returnin;
}
}

10. 怎么用java实现验证码

1、网上有JS插件啊,这个用java实现的话还是比较麻烦哦,需要java调用画图。我有一个写好的例子,是java和servlet做的。

2、亲们,这个验证码我做了很久才弄出来的,希望大家别介意我收费哦!

阅读全文

与java写验证码相关的资料

热点内容
为什么安卓机拍照那么丑 浏览:694
服务器绑定云产品实例 浏览:313
程序员认真工作被开除 浏览:453
程序员送苹果 浏览:143
小程序绘图源码 浏览:968
如何购买域名和服务器阿里云 浏览:671
服务器地址及端口在哪里 浏览:695
腾讯云服务器有危险吗 浏览:798
复制文件到文件夹php 浏览:10
java注释正则表达式 浏览:858
java连接远程oracle 浏览:91
javamainargs 浏览:758
金华数据文档加密软件公司 浏览:855
内心极度担心解压的音乐 浏览:897
穿搭技巧app卡色配什么颜色 浏览:595
程序员得结石 浏览:131
查公司薪资的app叫什么 浏览:410
压缩包多个文件夹图片连续看 浏览:487
linuxmysql无法用命令启动 浏览:442
地税身份认证用什么ApP 浏览:531