客户端代码:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta charset=utf-8>
<script type="text/javascript">
/*点击更新验证码 */
window.onload=function(){
var img=document.getElementById("sn");
img.onclick=function(){
img.src="<%=path%>/YanZhengAction?"+Math.random();
}
}
</script>
</head>
<body>
<form action="" method="">
用户名:<input type="text" name="username"/><br/>
密码:<input type="text" name="password"/><br/>
验证码:<input type="text" name="yanzhengma"/><img id="sn" src="<%=path%>/YanZhengAction"/><span>看不清?点击图片换一张</span><br/>
<input type="submit" value="登录"/>
</form>
</body>
</html>
服务器端代码:
package com.min.action;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/YanZhengAction")
public class YanZhengAction extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("image/jpeg");
//创建图片缓冲
BufferedImage img=new BufferedImage(90,40,BufferedImage.TYPE_INT_BGR);
//得到图片的画笔
Graphics2D gd=(Graphics2D)img.getGraphics();
//画图片大小及背景色
gd.setColor(Color.white);
gd.fillRect(0,0,90,40);
//画图片边框及颜色
gd.setColor(Color.red);
gd.drawRect(0,0,88,38);
//调用randomString()方法,随机生成4位的字符串
String sn=randomString(4);
//将生成的字符串放到session中,方便验证时取出
request.getSession().setAttribute("sn", sn);
//设置字体格式
gd.setFont(new Font("微软雅黑",Font.BOLD,25));
//定义一个颜色数组
Color [] colors={Color.black,Color.blue,Color.cyan,Color.gray,Color.green,Color.orange,Color.red,Color.pink};
int [] sk={1,-1};
//循环遍历字符串,给每个字符随机设置倾斜度和颜色,并画到图片上
for(int i=0;i<sn.length();i++){
int index=new Random().nextInt(colors.length);
gd.setColor(colors[index]);
int k=new Random().nextInt(sk.length);
//随机获得度数
double du=(new Random().nextInt(35)+10)*Math.PI/180*sk[k];
//设置字符的倾斜度
gd.rotate(du, 20*i+5, 10);
gd.drawString(sn.charAt(i)+"", 5+20*i, 25);
//清除倾斜度,避免对下一个字符造成影响
gd.rotate(-du, 20*i+5, 5);
}
//干扰线
for(int i=0;i<50;i++){
int x1=new Random().nextInt(img.getWidth());
int y1=new Random().nextInt(img.getHeight());
int x2=new Random().nextInt(10)+x1;
int y2=new Random().nextInt(10)+y1;
int index=new Random().nextInt(colors.length);
gd.setColor(colors[index]);
gd.drawLine(x1, y1, x2, y2);
}
//将图片输出到客户端
ImageIO.write(img, "jpeg", response.getOutputStream());
img.flush();
response.flushBuffer();
}
//获得随机字符串
public String randomString(int len){
String str="0123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM";
String ret="";
while(ret.length()<len){
int index=new Random().nextInt(str.length());
ret+=str.charAt(index)+"";
}
return ret;
}
}
效果截图:
