首页 > 代码库 > servlet中生成验证码

servlet中生成验证码

在servlet中生成验证码

package login;

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


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


import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
/**
 * 生成验证码servlet
 * @author Administrator
 *
 */
public class CheckCodeServlet extends HttpServlet {
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("service called");
/**1.设置服务器响应类型为jpg格式图片 */
response.setContentType("image/jpeg");
/**2.画图**/
//1.在内存中开辟空间存储图片
BufferedImage image = new BufferedImage(60,25,BufferedImage.TYPE_INT_RGB);
//2.获得画笔
Graphics g = image.getGraphics();
//3.准备随机数对象
Random r = new Random();
//4.设置图片背景色
g.setColor(new Color(r.nextInt(255),r.nextInt(255),r.nextInt(255)));
//5.填充
g.fillRect(0, 0, 60, 25);
//6.设置画笔前景色(设置字体颜色)
g.setColor(new Color(0,0,0));
//7.产生随机数
String number = String.valueOf(r.nextInt(99999)+1000);
/**将验证码存放session中*/
HttpSession session =request.getSession();
session.setAttribute("checkcode", number);
//8.数字画到图片上
g.drawString(number, 15,15);
g.drawLine(r.nextInt(20), r.nextInt(20), r.nextInt(50), r.nextInt(50));
g.drawLine(r.nextInt(20), r.nextInt(20), r.nextInt(50), r.nextInt(50));
g.drawLine(r.nextInt(20), r.nextInt(20), r.nextInt(50), r.nextInt(50));
g.drawLine(r.nextInt(20), r.nextInt(20), r.nextInt(50), r.nextInt(50));
/**3.使用特定格式压缩图片并输出*/
//1.建立文件输出流
OutputStream os =response.getOutputStream();
//2.使用指定格式
JPEGImageEncoder encoder =JPEGCodec.createJPEGEncoder(os);
encoder.encode(image);

}


}


在jsp页面使用java产生的验证码:

<td style="width:80px">
验证码:
</td>
<td valign="middle" >
<input name="validatecode" size="7px"/>
<img src=http://www.mamicode.com/"checkcode" id="img">
<a href="javascript:;" onclick="document.getElementById(‘img‘).
src=http://www.mamicode.com/‘checkcode?‘+new Date().getTime();">看不清,换一张
<br/>
<span style="color:red;">
<%
String check_error=(String)request.getAttribute("check_error");
%>
<%=check_error==null?"":check_error%>
</span>
</td>



在xmd文件里面的配置

<servlet>
    <servlet-name>check</servlet-name>
    <servlet-class>login.CheckCodeServlet</servlet-class>
  </servlet>


<servlet-mapping>
    <servlet-name>check</servlet-name>
    <url-pattern>/checkcode</url-pattern>
  </servlet-mapping>

进行验证判断的部分代码:

String validatecode=request.getParameter("validatecode");//验证码

String checkCode=(String)session.getAttribute("checkcode");

在servlet里面进行比较