案例:验证码的生成
@WebServlet("/checkCodeServlet")
public class CheckCodeServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int width =100;
int height = 50;
BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_ARGB);
Graphics g = image.getGraphics();
g.setColor(Color.PINK);
g.fillRect(0,0,width,height);
g.setColor(Color.BLACK);
g.drawRect(0,0,width-1,height-1);
String str = "abcdefghijklmnopqrstuvwxyz" +
"ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "0123456789";
Random random = new Random();
for (int i = 1; i <= 4; i++) {
int index = random.nextInt(str.length());
char ch = str.charAt(index);
g.drawString(ch+"",width/5*i,height/2);
}
g.setColor(Color.BLUE);
for (int i = 1; i <= 10; i++) {
int x1 = random.nextInt(width);
int x2 = random.nextInt(width);
int y1 = random.nextInt(height);
int y2 = random.nextInt(height);
g.drawLine(x1,y1,x2,y2);
}
ImageIO.write(image,"jpg",response.getOutputStream());
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
}
案例:验证码点击切换
- 在前者的Servlet基础上写一个HTML页面,用JS实现动态切换
- 代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>注册</title>
<script>
window.onload = function(){
var a = document.getElementById("change");
a.onclick = function(){
var daye = new Date().getTime();
var img = document.getElementById("checkImg")
img.src = "/duing2/checkCodeServlet?"+date;
}
}
</script>
</head>
<body>
<img id="checkImg" src="/duing2/checkCodeServlet" />
<a id="change" href="">看不清,换一张</a>
</body>
</html>