首页 > 代码库 > java制作验证码

java制作验证码

建立一个web工程

技术分享

编写servlet,生成图像

package com.imooc;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 ImageSevlet extends HttpServlet{    public void  doGet(HttpServletRequest request,HttpServletResponse response) throws IOException    {        System.err.println("doget into");                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 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();        Random r = new Random();        //获取随机的4个类        int len = ch.length, index;//len-1是ch下标的取值上限                StringBuffer sb = new StringBuffer();        for(int i = 0; i < 4 ; i++)        {            index = r.nextInt(len);            //获取随机位置,即获取到了字符            //,new 一个新的颜色,不让字符的颜色一致,随机取,            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("verifyCode", sb.toString());        //输出到response中,write(RenderedImage im, String formatName, OutputStream output)         ImageIO.write(bi, "jpg", response.getOutputStream());    }    }

web.xml

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">  <display-name>verifyCode</display-name>  <welcome-file-list>    <welcome-file>index.html</welcome-file>    <welcome-file>index.htm</welcome-file>    <welcome-file>index.jsp</welcome-file>    <welcome-file>default.html</welcome-file>    <welcome-file>default.htm</welcome-file>    <welcome-file>default.jsp</welcome-file>  </welcome-file-list>  <servlet>    <description></description>    <display-name>ImageSevlet</display-name>    <servlet-name>ImageSevlet</servlet-name>    <servlet-class>com.imooc.ImageSevlet</servlet-class>  </servlet>  <servlet-mapping>    <servlet-name>ImageSevlet</servlet-name>    <url-pattern>/servlet/ImageSevlet</url-pattern>  </servlet-mapping></web-app>

jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%>        <%    String nameSpace = request.getContextPath();%><%    String projectPath = request.getScheme() + "://"            + request.getServerName() + ":" + request.getServerPort()            + nameSpace + "/";%><%--以后可以在页面直接使用$("basepath") --%><%-- <c:set value="<%=projectPath %>" var="basePath"/> --%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title><script type="text/javascript">function  reloadCode(){    //解决缓存的问题    var time = new Date().getTime();    //在路径后面加上时间是因为这样每次请求的url不一样,浏览器就不会缓存,如果有缓存的影响那么图片就不会刷新    document.getElementById("verifyCode").src="<%=projectPath %>servlet/ImageSevlet?id="+time;    }</script></head><body>验证码:<input type="text" name = "verifyCode"/><img id="verifyCode" src="<%=projectPath %>servlet/ImageSevlet" alt="verifyCode"> <a href="javascript:reloadCode();"> 看不清,刷新</a><br></body></html>

效果(把浏览器放大了的效果)

技术分享

后台验证

package com.imooc;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class LoginServlet extends HttpServlet{    @Override    public void doGet(HttpServletRequest req, HttpServletResponse resp)            throws ServletException, IOException    {        String verifyCode = (String) req.getSession().getAttribute("verifyCode");        String code = req.getParameter("verifyCode");        System.out.println(verifyCode);        System.out.println(code);        System.out.println(verifyCode.equalsIgnoreCase(code));        //设置页面类型,解决中文乱码的问题        resp.setContentType("text/html;charset=gbk");        PrintWriter out = resp.getWriter();        if(verifyCode.equalsIgnoreCase(code))        {            out.print("success");        }        else        {            out.print("false");        }    }}

在web.xml中加入servlet

<servlet>    <description></description>    <servlet-name>LoginServlet</servlet-name>    <servlet-class>com.imooc.LoginServlet</servlet-class>  </servlet>  <servlet-mapping>    <servlet-name>LoginServlet</servlet-name>    <url-pattern>/servlet/LoginServlet</url-pattern>  </servlet-mapping>

修改上面的jsp,实际就是加入了form

<form action="<%=projectPath %>servlet/LoginServlet" method="get">验证码:<input type="text" name = "verifyCode"/><img id="verifyCode" src="<%=projectPath %>servlet/ImageSevlet" alt="verifyCode"> <a href="javascript:reloadCode();"> 看不清,刷新</a><br><input type="submit" value="submit"></form>

 

java制作验证码