java生成验证码并可刷新

时间:2024-01-01 19:23:33

手心创建一个简单的页面来显示所创建的验证码

<body>
<form action="loginName.mvc" method="post">
用户名:<input type="text" name="name" id="name"/><br/>
密码:<input type="password" name="password" id="password"/><br/>
验证码1:<a href="javascript:changePicture1();" title='看不清楚,换个图片'><img id="checkcode1" src=""><a href="javascript:changePicture1();" class="login-text03" title='看不清楚,换个图片'>看不清楚,换个图片</a><br/>
验证码2:<a href="javascript:changePicture2();" title='看不清楚,换个图片'><img id="checkcode2" src=""><a href="javascript:changePicture2();" class="login-text03" title='看不清楚,换个图片'>看不清楚,换个图片</a><br/>
验证码3:<a href="javascript:changePicture3();" title='看不清楚,换个图片'><img id="checkcode3" src=""><a href="javascript:changePicture3();" class="login-text03" title='看不清楚,换个图片'>看不清楚,换个图片</a>
<span id="spantext"></span><br/>
<!-- <input type="button" value="登录" onclick="loginPerson()"/>-->
<input type="submit" value="登录"/>
</form>
</body>
<script language="javascript">
window.onload=function(){
changePicture1();
changePicture2();
changePicture3();
}; function changePicture1(){
$("#checkcode1").attr("src","servlet/CheckCode?code="+Math.random());
}
function changePicture2(){
/* var arry=["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"];
var len=arry.length;
var code="";
for(i=0;i<=4;i++){
var index=Math.floor(Math.random()*len);
code+=arry[index];
} */
//alert(code);
$("#checkcode2").attr("src","servlet/ImageServlet?code="+Math.random());
}
function changePicture3(){
$("#checkcode3").attr("src","servlet/graphicsImage?code="+Math.random());
}
function loginPerson(){
var name=document.getElementById("name").value;
var password=document.getElementById("password").value;
if(name==""||password==""){
alert("账户名或密码不能为空");
$("#spantext").html("账户名或密码不能为空");
}else{
$.ajax({
type : "post",
url : "./loginName.mvc?name="+name+"&password="+password,
success : function(data){
alert(data);
var obj=eval("("+data+")");
var message=obj.code;
//var name=obj.name;
//var password=obj.password;
alert(message);
//alert(name);
//alert(password);
},
error : function(data){
$("#spantext").html("网络错误");
}
});
}
}
</script>

  在这里写有三个生成验证码的类,其实他们的本质是一样的  ,都是类似的

创建的第一个验证码
package com.chinasoft.ssm.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.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder; public class CheckCode extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request,response);
} public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { response.setContentType("image/jpeg");
// 图片的内存映像
BufferedImage image = new BufferedImage(60, 20,BufferedImage.TYPE_INT_BGR);
// 获取画笔对象
Graphics g = image.getGraphics();
//随机变换图片的颜色
Random r = new Random();
g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));
//开始绘制图片
g.fillRect(0, 0, 60, 20);
//将画笔颜色清零
g.setColor(new Color(0,0,0));
Font font = new Font("Verdana", Font.ITALIC|Font.BOLD, 16);
g.setFont(font);
String number = String.valueOf(r.nextInt(99999));
HttpSession session = request.getSession();
session.setAttribute("number", number);
g.drawString(number, 5, 15);
g.setColor(new Color(r.nextInt(255),r.nextInt(255),r.nextInt(255)));
//压缩jpeg格式转换为输出流的形式
OutputStream os = response.getOutputStream();
//把输出流对象中的图像信息编码
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os);
//向创建对象时指定的输出流输出
encoder.encode(image);
os.flush();
os.close();
} /**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
} }

package com.chinasoft.ssm.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.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 ImageServlet extends HttpServlet {
private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(request,response);
} public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String ch1= (String) request.getParameter("code");
System.out.println(ch1);
response.setContentType("image/jpeg");
// 图片的内存映像
BufferedImage bi=new BufferedImage(68, 22,BufferedImage.TYPE_INT_RGB);
//获得画笔对象
Graphics g=bi.getGraphics();
//图片的颜色选择
Color c=new Color(200,150,255);
g.setColor(c);
//开始绘制图片
g.fillRect(0, 0, 68, 22); char[] ch="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
Random r=new Random();
int len=ch.length;
int index;
StringBuffer sb=new StringBuffer();
for(int i=0;i<4;i++)
{
//获取一个随机数
index=r.nextInt(len);
//给字体设置颜色
Font font = new Font("Verdana", Font.ITALIC|Font.BOLD, 16);
g.setFont(font);
g.setColor(new Color(r.nextInt(88),r.nextInt(188),r.nextInt(255)));
//将所有选择的字体绘画出来
g.drawString(ch[index]+"",(i*15)+3, 18);
//将随机生成的验证码添加到可变字符sb中去
sb.append(ch[index]);
}
//将生成的验证码对象保存到piccode对应的value中去
//request.getSession().setAttribute("piccode", sb.toString());
//使用给定的支持格式将图像BufferedImage的bi对象写入到响应输出流当中
//ImageIO.write(bi, "JPG", response.getOutputStream()); OutputStream os = response.getOutputStream();
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os);
//向创建对象时指定的输出流输出
encoder.encode(bi);
os.flush();
os.close();
} }

创建的第二个验证码

package com.chinasoft.ssm.servlet;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
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; public class graphicsImage extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { doPost(request,response);
} public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
char[] strs = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
BufferedImage bi = new BufferedImage(150,40,BufferedImage.TYPE_INT_RGB);
Graphics2D g = (Graphics2D)bi.getGraphics();
Random num=new Random();
Color color ;
int len = strs.length;
g.setColor(Color.WHITE);
g.fillRect(0,0,150,40);
// 随机画干扰的蛋蛋
for(int i=0;i<15;i++){
color =new Color(150,100, 250);
g.setColor(color);
// 画蛋蛋,有蛋的生活才精彩
g.drawOval(num.nextInt(150), num.nextInt(40), 5+num.nextInt(10), 5+num.nextInt(10));
color = null;
}
Font font = new Font("Verdana", Font.ITALIC|Font.BOLD, 28);
g.setFont(font);
/* 画字符串 */
for(int i=0;i<6;i++)
{
int index=num.nextInt(len);
// 指定透明度
AlphaComposite ac3 = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.7f);
g.setComposite(ac3);
// 对每个字符都用随机颜色
color = new Color(20 + num.nextInt(110), 20 + num.nextInt(110), 20 + num.nextInt(110));
g.setColor(color);
g.drawString(strs[index]+"",(i*15)+40, 40-4);
color = null;
ac3 = null;
}
ImageIO.write(bi, "png", response.getOutputStream());
}
public void init() throws ServletException {
// Put your code here
} }

创建的第三个验证码