效果图
jsp实现登录验证码_随机数
目录结构
jsp实现登录验证码_html_02

login.jsp
<form action="<%= request.getContextPath()%>/servlet/UserServlet" method="post" >
		username1:<input type="text" name="uname" />
		pwd1:<input type="password"  name="upwd" />
	    <br>
	       验证码:<input  type="text" name="checkCode"/>
	    <a href="javascript:reloadCode();">
	    <img alt="验证码" id="imagecode" src="<%= request.getContextPath()%>/servlet/ImageServlet"/>
	       看不清楚</a><br>
	    <input type="submit" value="提交">
   </form>
辅助js
<script type="text/javascript">
function reloadCode()
     {
         var time=new Date().getTime();
         document.getElementById("imagecode").src="<%= request.getContextPath()%>/servlet/ImageServlet?d="+time;
     }
</script>
ImageServlet 图像
package com.bennyrhys.bean;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(urlPatterns="/servlet/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 Color(200,150,255); //创建颜色
         /*根据背景画了一个矩形框
          */
         g.setColor(c);//为画布创建背景颜色
         g.fillRect(0, 0, 68,22); //fillRect:填充指定的矩形
         
         char[] ch="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();//转化为字符型的数组
         Random r=new Random();
         int len=ch.length;
         int index; //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]);
         }
         request.getSession().setAttribute("piccode",sb.toString()); //将数字保留在session中,便于后续的使用
         ImageIO.write(bi, "JPG", response.getOutputStream()); 
    }}
UserServlet验证
package com.bennyrhys.bean;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class UserServlet
 */
@WebServlet(urlPatterns="/servlet/UserServlet")
public class UserServlet extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("do Post");
		String uname = request.getParameter("uname");
		String upwd = request.getParameter("upwd");
		System.out.println(uname+"----"+upwd);
		/*if ("root".equals(uname) && "root".equals(upwd)) {
			//提示成功登录
			System.out.println("yes");
			//传输session数据
			HttpSession session = request.getSession();
			session.setAttribute("uname", uname);
			session.setAttribute("upwd", upwd);
			//转跳页面
			String contextPath = request.getContextPath();
			response.sendRedirect(contextPath+"/index.html");
		}else {
			System.out.println("no");
			request.getRequestDispatcher("/login.html").forward(request, response);
		}*/
		
		
		//验证码
		 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) && "root".equals(uname) && "root".equals(upwd))
	        {
	            out.println("验证码输入正确!");
	          //提示成功登录
				System.out.println("yes");
				//传输session数据
				HttpSession session = request.getSession();
				session.setAttribute("uname", uname);
				session.setAttribute("upwd", upwd);
				//转跳页面
				String contextPath = request.getContextPath();
				response.sendRedirect(contextPath+"/index.html");
	        }
	        else
	        {
	            out.println("验证码输入错误!!!");
	            System.out.println("no");
				request.getRequestDispatcher("/login.jsp").forward(request, response);
	        }
	        out.flush();//将流刷新
	        out.close();//将流关闭
		
	}

}

PS:本文原创首发于公众号「让我遇见相似的灵魂」,回复关键字获取数十本程序员经典电子书。

左手代码,右手吉他,这就是天下:如果有一天我遇见相似的灵魂 那它肯定是步履艰难 不被理解 喜黑怕光的。如果可以的话 让我触摸一下吧
它也一样孤独得太久。 不一样的文艺青年,不一样的程序猿。

jsp实现登录验证码_随机数_03