龙空技术网

如何使用javaweb写一个验证码

滴滴滴程序员 43

前言:

现时各位老铁们对“java短信验证码实现”大致比较关切,兄弟们都想要了解一些“java短信验证码实现”的相关知识。那么小编同时在网上搜集了一些关于“java短信验证码实现””的相关知识,希望各位老铁们能喜欢,兄弟们快快来了解一下吧!

package cn.itcast.servlet.web;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.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;/** * Servlet implementation class CheckCodeServlet */@WebServlet("/CheckCodeServlet")public class CheckCodeServlet extends HttpServlet {	private static final long serialVersionUID = 1L;           /**     * @see HttpServlet#HttpServlet()     */    public CheckCodeServlet() {        super();        // TODO Auto-generated constructor stub    }	/**	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)	 */	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {		//1.创建一个对象,这个对象在内存中就代表图片(验证码图片对象)		int width=100;		int height=50;		BufferedImage image=new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);		//2.美化图片		//2.1填充图片颜色		Graphics g = image.getGraphics();//获取画笔的对象		g.setColor(Color.pink);//设置画笔的颜色		g.fillRect(0, 0, width, height);//填充图片		//2.2画边框		g.setColor(Color.blue);		g.drawRect(0, 0, width-1, height-1);				String str="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";		//生成随机角标		Random ran=new Random();		for (int i = 1; i <=4; i++) {			int index = ran.nextInt(str.length());			//获取字符			char ch = str.charAt(index);			//2.3写验证码			g.drawString(ch+"",width/5*i,height/2);		}		//2.4画干扰线		g.setColor(Color.green);		//随机生成坐标点		for (int i = 0; i < 10; i++) {			int x1=ran.nextInt(width);//生成一个0-width的随机值,不包括width			int x2=ran.nextInt(width);			int y1=ran.nextInt(height);			int y2=ran.nextInt(height);			g.drawLine(x1, x2, y1, y2);		}								//3.将图片输出到页面展示		//将内存中的图片输出到页面		ImageIO.write(image, "jpg", response.getOutputStream());	}	/**	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)	 */	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {		// TODO Auto-generated method stub		doGet(request, response);	}}

视频加载中...

标签: #java短信验证码实现 #java生成随机数字验证码 #java设置rgb #javaweb短信验证码 #java web 短信验证码