验证码案例
package Response;
import javax.imageio.ImageIO;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
@WebServlet(name = "Servlet1", value = "/Servlet1")
public class Servlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.创建对象,在内存中图片
int weith=100;
int height=50;
BufferedImage image=new BufferedImage(weith,height,BufferedImage.TYPE_INT_RGB);
//2.美化图片
//2.1填充背景色
Graphics graphics = image.getGraphics();//画笔对象
graphics.setColor(Color.PINK);
//2.2画边框
graphics.fillRect(0,0,weith,height);
graphics.setColor(Color.BLUE);
graphics.drawRect(0,0,weith-1,height-1);
String str="qwertyuiopasdfghjklzxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM1234567890";
//生成随机角标
Random ran=new Random();
for(int i=1;i<=4;i++){
int index=ran.nextInt(str.length());
//获取字符
char ch=str.charAt(index);//随机字符
//2.3写验证码
graphics.drawString(ch+"",weith/5*i,height/2);
}
//2.4画干扰线
graphics.setColor(Color.green);
//随机生成坐标点
int x1=ran.nextInt(weith);
int x2= ran.nextInt(weith);
int y1=ran.nextInt(height);
int y2= ran.nextInt(height);
graphics.drawLine(x1,x2,y1,y2);
//3.将图片输出到页面展示
ImageIO.write(image,"jpg",response.getOutputStream());
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
/*分析:
点击超链接或者图片,需要换一张
1.给超链接和图片绑定单击事件
2.重新设置图片的src属性值
*/
window.onload=function (){
//1.获取图片对象
var img=document.getElementById("checkCode");
//2.绑定单击事件
img.onclick=function (){
//加时间戳
var date=new Date().getTime();
img.src="Response_war_exploded/Servlet?"+date;
}
}
</script>
</head>
<body>
<img id="checkCode" src="/Response_war_explodedServlet1";/>
<a id="cahnge" href="/Response_war_exploded/Servlet">看不清换一张</a>
</body>
</html>