需求:制作验证码
第一种:不利用外部插件做的验证码
步骤:
1
<head>
<script type="text/javascript"> //这是在看不清楚验证码时重新生成验证码的JS实现
function reload(){
var time = new Date().getTime();
document.getElementById("imagecode").src="servlet/imageservlet?d"+time;
}
</script>
....
....
</head></span>
<body>
<form action="servlet/Loginservlet" method="get">
验证码:<input type="text" name="checkcode">
<img alt="验证码" id="imagecode" src="servlet/imageservlet">//由imageservlet来生成验证码
<a href="javascript:reload()">看不清楚</a>//看不清楚时调用JS
<input type="submit" value="提交">
</form>
<%//这段代码的作用是在我们输入错误的验证码的时候在index.jsp本页显示错误信息,而不是跳转到其他
//页面
PrintWriter pw = response.getWriter();
String flag = (String)request.getSession().getAttribute("fail");
if(flag!=null){
if(flag.equals("fail")){
pw.write("失败");
}
}
%>
</body>
2 编写imageservlet类
主要代码就是doget的书写
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//既然是生成图片,所以用到 BufferedImage
BufferedImage bi = new BufferedImage(68, 22, BufferedImage.TYPE_INT_RGB);
//绘制图像的类
Graphics gra = bi.getGraphics();
// 既然绘制图像,所以肯定有颜色
Color col = new Color(200, 120, 255);
gra.setColor(col);<strong>//设置颜色</strong>
gra.fillRect(0,0, 68, 22);<strong>//设置验证码图片的形状</strong>
char[] ch="ABCDEFG1234567890".toCharArray();<strong>//我们验证码的备选内容</strong>
Random ran = new Random();<strong>//设置随机数,从备选内容中随机选取</strong>
int len = ch.length;
int index;
StringBuffer sb = new StringBuffer();<strong>//StringBuffer的作用是保存将我们从备选内容中选取的元素,以备后来的验证</strong>
for(int i=0;i<4;i++){<strong>//这段代码是生成4个元素的验证码</strong>
index = ran.nextInt(len);
gra.setColor(new Color(ran.nextInt(88), ran.nextInt(188), ran.nextInt(255)));
gra.drawString(ch[index]+"", (i*15)+3, 18);
sb.append(ch[index]);<strong>//将选取的元素存储起来</strong>
}
// 设置干扰线
for (int i = 0; i < 10; i++) {
int xs = ran.nextInt(1);
int ys = ran.nextInt(68);
int xe = xs + ran.nextInt(68);
int ye = ys + ran.nextInt(22);
gra.setColor(new Color(ran.nextInt(88), ran.nextInt(188), ran.nextInt(255)));
gra.drawLine(xs, ys, xe, ye);
}
request.getSession().setAttribute("imagecode",sb.toString());<strong>//验证码元素保存到session中,以用来验证</strong>
ImageIO.write(bi, "JPG", response.getOutputStream());//将验证码写出去
}
3,书写Loginservlet代码验证输入的正确与否
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String imagecode = (String)request.getSession().getAttribute("imagecode");//从session中提取我们在Imagesevlet中保存的验证码元素
String checkcode = request.getParameter("checkcode");//提取我们在index,jsp中填写的验证码
response.setContentType("text/html; charset=utf-8");//设置编码格式,否则下面的汉字无法正确输出
PrintWriter out = response.getWriter();
if(checkcode.equals(imagecode)||checkcode.equals(imagecode.toLowerCase())){//判断书写的验证码和实际的是否相同
out.write("验证成功");
}else{
request.getSession().setAttribute("fail", "fail");//如果不同则重定向到index.jsp页面,并在index页面中输出错误提示,其实这里可以写的
//更好,自己只是随便写的
//request.getRequestDispatcher("/index.jsp").forward(request, response);
response.sendRedirect(request.getContextPath()+"/index.jsp");
}
}