最近在学servlet的知识,了解了验证码的编写。再写一 遍加深印象!
//前面的导包什么的就不写了,IDE都会自动生成直接进入Servlet的编写吧
@WebServlet("/checkcode")
public class CheckCode extends HttpServlet
{
protected void doGet(HttpServletRequest request, HttpServletResponse response){
//创建图片对象,相当于一个画板,并在构造函数中传入宽、高、图片类型
BufferedImage img=new BufferedImage(90, 30,BufferedImage.TYPE_INT_BGR);
//通过img对象获取画图对象
Graphics pen=img.getGraphics();
//提前这设置好验证码会用到的字符
String[] codes=
{"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" ,"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"};
//创建随机数对象用于生成4位随机字符
Random random=new Random();
//声明一个字符串用在放生成的随机字符
String code="";
for(int i=0;i<=3;i++){
//随机生成四次连接到code字符串61代表数组长度
code=code+codes[random.nexInt(61)];
}
//设置文字颜色
pen.setColor(Color.BULE);
//向画板生成验证码,分别传入字符串以及绘画的位置
pen.drawString(code,20,15);
//简单生成以后可以向页面输出,传入“画板”对象,输出图片的格式,输出流;
ImageIo.write(img,"jpg",response.getOutputStream());
ImageIO.write(img, "jpg", response.getOutputStream());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
以上一个简陋的验证码Servlet就编写好了,还可以加上干扰线,已经字体旋转等,可以去查一下JavaEE的API进行实现。打一遍只为自己熟悉。现在都是用点击图片以及拖拉拼图条进行验证了,这个基本快被淘汰了。希望自己以后如果有机会从事这个行业再去学习!!!!!