Jsp+Servlet之验证码的制作和验证(一)
方法一:BufferedImage+Graphics制作验证码
1.制作JSP页面(如图)
代码如下:
<body> <form action="<%=request.getContextPath()%>/servlet/LoginServlet" method="get" /> 验证码:<input type="text" name="checkcode"/> <img alt="验证码" id="imagecode" src="<%=request.getContextPath()%>/servlet/ImageServlet"/> <a href="javascript:reloadCode();">看不清楚</a><br> <input type="submit" value="提交"> </form> </body>
2.实现ImageServlet
public class ImageServlet extends HttpServlet { public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException{ //制作图片 BufferedImage bi=new BufferedImage(68,22,BufferedImage.TYPE_INT_RGB); Graphics g=bi.getGraphics(); //设置颜色并绘制 Color c=new java.awt.Color(200, 150, 255); g.setColor(c); g.fillRect(0, 0, 68, 22); //设置内容 char ch[]="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray(); //随机数--通过随机数随机产生颜色和字母、数字 Random r=new Random(); int len=ch.length,index; StringBuffer sb=new StringBuffer(); for(int i=0;i<4;i++){ //随机产生字母、数字 index=r.nextInt(len); //随机产生颜色 g.setColor(new Color(r.nextInt(88),r.nextInt(188),r.nextInt(255))); //画出字母、数字 g.drawString(ch[index]+"", (i*15)+3, 18); //存储当前字母、数字 sb.append(ch[index]); } //将当前字母、数字存入session request.getSession().setAttribute("piccode", sb.toString()); //输出图片 ImageIO.write(bi, "JPG", response.getOutputStream()); } }
3.实现点击“看不清楚”换一张图片(修改Jsp)
**在form标签前、body标签内插入:
<script type="text/javascript"> function reloadCode(){ //通过time来区分不同的时间,从而刷新验证码图片 var time=new Date().getTime(); document.getElementById("imagecode").src="<%=request.getContextPath()%>/servlet/ImageServlet?d="+time; } </script>
**注:其中,必须加入time来区分不同的路径,否则浏览器中会有缓存,点击之后还是原来的图!!
4.实现验证码的验证(实现LoginServlet)
public class LoginServlet extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response)throws IOException{ //获取图片内容 String piccode=(String)request.getSession().getAttribute("piccode"); //获取输入内容 String checkcode=request.getParameter("checkcode"); //不区分大小写 checkcode=checkcode.toUpperCase(); //防止乱码 response.setContentType("text/html;charset=gbk"); PrintWriter out=response.getWriter(); //验证并输出结果 if(checkcode.equals(piccode)){ out.println("验证码输入正确!"); }else{ out.println("验证码输入错误!!"); } out.flush(); out.close(); } }
--未完待续--
**注:学习自慕课网《Java实现验证码制作》,附链接https://www.imooc.com/learn/283