servlet awt随机图片验证码

package rd.test;

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

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//输出一张图片
public class Test1 extends HttpServlet {

	public static final int WIDTH = 120;
	public static final int HEIGHT = 35;
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		BufferedImage image = new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_RGB);

		Graphics g = image.getGraphics();
		
		//1,设置背景色
		setBackGround(g);
		
		//2,设置边框
		setBorder(g);
		
		//3,画干扰线
		drowRandomLine(g);
		
		//4,写随机数
		//drawRandomNum(g);
		String random = drawRandomNum2d((Graphics2D)g);//验证相关
          request.getSession().setAttribute("checkcode",random);//验证相关		
//5,图形写给浏览器 response.setContentType("image/jpeg"); //控制浏览器不要缓存随机验证码图片,让它每次都更新 response.setDateHeader("expries", -1); response.setHeader("Cache-Control","no-cache"); response.setHeader("Pragma","no-cache"); ImageIO.write(image, "jpg", response.getOutputStream()); } private void drowRandomLine(Graphics g) { // TODO Auto-generated method stub g.setColor(Color.GRAY); for(int i = 0;i<5;i++) { int x1 = new Random().nextInt(WIDTH-2)+2; int y1 = new Random().nextInt(HEIGHT-2)+2; int x2 = new Random().nextInt(WIDTH-2)+2; int y2 = new Random().nextInt(HEIGHT-2)+2; g.drawLine(x1, y1, x2, y2); } } private String drawRandomNum2d(Graphics2D g) { // TODO Auto-generated method stub g.setColor(Color.RED); g.setFont(new Font("宋体",Font.BOLD,20)); //[u4e00-u9fa5] String base = "一二三四五六七八九十百千万兆亿啊我饿依无余";           StringBuffer sb = new StringBuffer();//验证相关
int x = 5; for(int i = 0;i<4;i++) { int degree = new Random().nextInt()%30; String ch = "" + base.charAt(new Random().nextInt(base.length())); sb.append(ch);//验证相关
              g.rotate(degree*Math.PI/180, x, 25);//设置旋转幅度 g.drawString(ch, x, 25); g.rotate(-degree*Math.PI/180, x, 25);//转回去 x+=30; }
          return sb.toString(); } private void drawRandomNum(Graphics g) { g.setColor(Color.RED); g.setFont(new Font("宋体",Font.BOLD,20)); //[u4e00-u9fa5] String base = "一二三四五六七八九十百千万兆亿啊我饿依无余"; int x = 5; for(int i = 0;i<4;i++) { String ch = "" + base.charAt(new Random().nextInt(base.length())); g.drawString(ch, x, 20); x+=30; } } private void setBorder(Graphics g) { g.setColor(Color.BLUE); g.drawRect(1, 1, WIDTH-2, HEIGHT-2); } private void setBackGround(Graphics g) { // TODO Auto-generated method stub g.setColor(Color.WHITE); g.fillRect(0, 0, WIDTH, HEIGHT); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }
<%@ 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 changeImg(img){
            img.src = img.src + "?" + new Date().getTime();
        }
    </script>
    
  </head>
  
  <body>
  
      <form action="/web/servlet/check" method="post">
          用户名:<input type="text" name="username">
          密码 :<input type="password" name="password"><br/><br/>
          验证码:<input type = "text" name="checkcode">
          <img src="http://localhost:8080/random/servlet/Test1" onclick="changeImg(this)"/>
          <input type="submit" value="注册">
      </form> 
  </body>
</html>

check:

request.setCharacterEncoding("UTF-8");

String c_checkcode = request.getParameter("checkcode");

String s_checkcode = request.getSession().getAttribut("checkcode");

if(c_checkcode!=null && s_checkcode!=null && c_checkcode.equals(s_checkcode)){

  System.out.println("处理注册请求“);

}else{

  System.out.println("验证码错误");

}

原文地址:https://www.cnblogs.com/flying607/p/3451042.html