基于servlet的验证码

基于servlet的验证码,第1张

基于servlet的验证码

上代码 seccodeServlet.java

package com.zheng;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.PrintWriter;
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;
import javax.servlet.http.HttpSession;

public class seccodeServlet extends HttpServlet {
	private static final int width=200;
	private static final int height=50;
	private  static final String code ="abcdefghijklmnopqrstuvwxyz";
	private Random random= new Random();
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("image/jpeg");
				BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_3BYTE_BGR);
				Graphics g = image.getGraphics();
				g.setColor(getColor(200,40));
				g.fillRect(0,0,width,height);
				//随机画线
				for(int i= 0;i<20;i++){
					int x1 = random.nextInt(width);
					int y1 = random.nextInt(height);
					int x2 = random.nextInt(width);
					int y2 = random.nextInt(height);
					g.setColor(getColor(160,40));
					g.drawLine(x1,y1,x2,y2);
				}
				
				//输出字符
				String seccode="";
				Font font = new Font("宋体",Font.ITALIC,width/4);
				g.setFont(font);
				for(int i= 0;i<4;i++){
					char c= code.charAt(random.nextInt(code.length()));
				seccode +=c;
				g.drawString(c+"",i* width/4+5 , 40);		
				}
				
				HttpSession session = request.getSession();
				session.setAttribute("seccode",seccode);
				
				ImageIO.write(image,"JPEG",response.getOutputStream());
				g.dispose();
	}
	private Color getColor(int base,int inc){
		int r=base+random.nextInt(inc);
		int g=base+random.nextInt(inc);
		int b=base+random.nextInt(inc);
		return new Color(r,g,b);
	}

	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		
	}

}

web.xml中servlet的配置



  
    This is the description of my J2EE component
    This is the display name of my J2EE component
    seccodeServlet
    com.zheng.seccodeServlet
  

  
    seccodeServlet
    /servlet/seccodeServlet
  
  
    index.jsp
  

运行结果上图

 

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5435645.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-11
下一篇 2022-12-11

发表评论

登录后才能评论

评论列表(0条)

保存