前端代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="/ServletDemo2/LoginDemo" method="get">
账号<input type="text" name="number" /><br>
密码<input type="password" name="password" /><br>
验证码<input type="text" name="imagecode" /><br>
<img id="imagecode" src="/ServletDemo2/ImageServlet">
<!-- href中的#是一种临时连接的写法,这样写代表这个连接目前不可用,
点击了也不会有作用,还是会跳转到本页。只有当#被有效连接替换才会有作用 -->
<a href="#" onclick="run()">看不清,换一张</a>
<input type="submit" value="Login" />
</form>
</body>
<script type="text/javascript">
function run() {
var image = document.getElementById("imagecode");
image.src = "/ServletDemo2/ImageServlet?"+new Date().getTime();
}
</script>
</html>
后台
这部分的干扰线的分辨率坐标被我改的不对了,自己改吧(那样就要根据自己的要求写好image的大小,g画图象的位置,没有难度)。
package com.xml.response;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
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.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 验证码
*/
public class ImageServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//生成图片区域
BufferedImage image = new BufferedImage(150, 50, BufferedImage.TYPE_INT_RGB);
//获取画笔对象
Graphics2D g = (Graphics2D) image.getGraphics();
g.setColor(Color.PINK);
g.fillRect(0, 0, 150, 50);
int x = 0;
int y = 0;
String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
g.setColor(Color.black);
g.setFont(new Font("隶书", Font.BOLD, 20));
Random ran = new Random();
for(int i = 0;i<4;i++) {
int index = ran.nextInt(62);
//获取弯曲角度
int jiaodu = ran.nextInt(60)-30;
double hudu = jiaodu*Math.PI/180;
g.rotate(hudu,x,y+20);
char ch = str.charAt(index);
g.drawString(""+ch, x, y+20);
g.rotate(-hudu, x, y);
x += 20;
}
//干扰线
g.setColor(Color.GREEN);
int x1,x2,y1,y2;
for(int i = 0;i<4;i++) {
x1 = 100+ran.nextInt(150);
x2 = 100+ran.nextInt(150);
y1 = 100+ran.nextInt(80);
y2 = 100+ran.nextInt(80);
g.drawLine(x1, y1, x2, y2);
}
//图片输出到浏览器端
ImageIO.write(image, "jpg", response.getOutputStream());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}