【验证码】servlet 生成 验证码图片

来源:互联网 发布:有首单立减的外卖软件 编辑:程序博客网 时间:2024/05/16 11:00

getImageServlet : 生成验证码图片

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//获得一张图片// 创建图片 -- 在内存中int width = 80;int height = 40;BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);//创建图层,获得画板Graphics g = image.getGraphics();//确定画笔颜色g.setColor(Color.BLACK);//填充一个矩形g.fillRect(0, 0, width, height);//只需要一个边框//设置颜色g.setColor(Color.WHITE);//填充一个矩形g.fillRect(1, 1, width -2, height -2);//填充字符String data = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";//设置字体g.setFont(new Font("宋体",Font.BOLD,30));//缓存随机生成的字符StringBuffer buf = new StringBuffer();//随机获得4个字符Random random = new Random();for(int i = 0 ; i < 4 ; i++){//设置随机颜色g.setColor(new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255)));//获得一个随机字符int index = random.nextInt(62);//截取字符串String str = data.substring(index, index + 1);  //[)//需要将随机的字符,写到图片中g.drawString(str, 20 * i, 30);//缓存buf.append(str);}//将获得随机字符串,保存到session// * 获得sessionHttpSession session = request.getSession();// * 保存值session.setAttribute("number", buf.toString());//干扰线for(int i = 0 ; i < 10 ; i ++){//设置随机颜色g.setColor(new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255)));//随机画直线g.drawLine(random.nextInt(width), random.nextInt(height), random.nextInt(width), random.nextInt(height));}/** * <extension>jpg</extension>        <mime-type>image/jpeg</mime-type> *///通知浏览器发送的数据时一张图片response.setContentType("image/jpeg");//将图片发送给浏览器ImageIO.write(image, "jpg", response.getOutputStream());}

loginServlet :验证码检验

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {request.setCharacterEncoding("UTF-8");response.setContentType("text/html;charset=UTF-8");//获得用户提交的数据 imageNumberString imageNumber = request.getParameter("imageNumber");//需要判断  从session获得保存的验证码的信息// * 获得sessionHttpSession session = request.getSession();// * 获得保存的值numberString number = (String)session.getAttribute("number");PrintWriter out = response.getWriter();//匹配 用户提交的数据与程序保存的数据if(number != null){ //程序保存if(number.equalsIgnoreCase(imageNumber)){//输入正确out.print("验证通过");} else {//验证码错误out.print("验证码错误");}//无论情况,程序存储的数据,只能使用一次session.removeAttribute("number");} else {out.print("验证码失效");}}


index.jsp 调用

 <form action="/test/loginServlet" method="post"> <input type="text" name="imageNumber" /> <img src="/test/getImageServlet"/> <br/> <input type="submit"/>  </form>

当cookie 禁用时,得对URL重写   

imageUrl = response.encodeURL(imageUrl);

0 0