本文主要是介绍使用servlet实现验证码--IMooC笔记,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
需要用到验证码时,调用生成验证码图片的servlet即可
生成图片
1.BufferedImage图像数据缓冲区
2.Graphics绘制图片
3.通过Random产生随机验证码信息
4.使用Graphics绘制图片
5.记录验证码信息到session中
6.使用ImageIO输出图片
校验验证码是否正确
1.获取页面验证码
2.获取session保存的验证码
3.比较验证码
4.返回校验结果
两个servlet一个是生成验证码的ImageServlet,另一个是校验验证码的LoginServlet
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"><display-name></display-name> <servlet><servlet-name>ImageServlet</servlet-name><servlet-class>com.nicolashe.ImageServlet</servlet-class></servlet><servlet-mapping><servlet-name> ImageServlet</servlet-name><url-pattern>/servlet/ImageServlet</url-pattern></servlet-mapping><servlet><servlet-name>LoginServlet</servlet-name><servlet-class>com.nicolashe.LoginServlet</servlet-class></servlet><servlet-mapping><servlet-name> LoginServlet</servlet-name><url-pattern>/servlet/LoginServlet</url-pattern></servlet-mapping><welcome-file-list><welcome-file>index.jsp</welcome-file></welcome-file-list>
</web-app>
生成验证码ImageServlet.java
package com.nicolashe;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.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;public class ImageServlet extends HttpServlet{public void doGet(HttpServletRequest request,HttpServletResponse response){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);//上面画了一个框/* *********************** */char[] ch="ABCDEFGHIJKLMNOPQRSTUVWXYZ01234546789".toCharArray();Random r=new Random();int len=ch.length;int 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());try {ImageIO.write(bi, "JPG", response.getOutputStream());} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}
校验验证码的LoginServlet.java:
package com.nicolashe;import java.io.IOException;
import java.io.PrintWriter;import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;public class LoginServlet extends HttpServlet {public void doGet(HttpServletRequest request,HttpServletResponse response){String piccode=(String)request.getSession().getAttribute("piccode");String checkcode=request.getParameter("checkcode");response.setContentType("text/html;charset=utf-8");checkcode=checkcode.toUpperCase();try {PrintWriter out=response.getWriter();if(checkcode.equals(piccode)){out.println("验证码正确");}else{out.println("验证码错误");}} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}
验证码输入页面index.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html><head><base href="<%=basePath%>"><title>My JSP 'index.jsp' starting page</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">--><script type="text/javascript">function reloadCode(){//备注是的代码不会使页面刷新,因为页面有缓存//document.getElementById("imagecode").src="<%=request.getContextPath()%>/servlet/ImageServlet"//给页面传递一个参数,时间参数,时间时刻在变化,所以每一次点击刷新都被浏览器认为是一次新的请求var time=new Date().getTime();document.getElementById("imagecode").src="<%=request.getContextPath()%>/servlet/ImageServlet?d="+time;}</script></head><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>
</html>
这篇关于使用servlet实现验证码--IMooC笔记的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!