在登陆页面写出一次性图片验证码

在登陆页面增加图片验证码

第一步:

生成随机图片验证码:

主要使用   imageio  以及  BufferedImage,注意我的生成的验证码图片保存路径在F盘,大家可以随意更改

/**
     * 此java文件主要用于生成随机的验证码图片,保存在F:/a.jpg
     */
    
    
    //最终的TestCode
    private static StringBuilder lastCode = new StringBuilder();
    
    //返回最终的TestCode
    public static StringBuilder getLastCode() {
        return lastCode;
    }

    //生成随机的字母
    public  void produceIdentifyCodeImage() {
        String code[] = {"3","4","5","z","x","c","v","b","n","m","a","s","d","f","g"};
        String codeType[] = {"TimesRoman","Courier","Arial",
                            "宋体","仿宋","微软雅黑","Monospaced ",
                            "TimesRoman","Courier","Arial"};
        
        int randomNum[] =  getRandomNum(4);
        
        
        if(lastCode.length()!=0) {
            lastCode.replace(0, lastCode.length(), "");
        }
        
        BufferedImage bi = new BufferedImage(130, 60, BufferedImage.TYPE_INT_BGR);
        Graphics2D g = (Graphics2D) bi.getGraphics();
        g.setColor(Color.white);
        g.fillRect(0, 0, 150, 70);
        for(int i=0;i<4;i++) {
            g.setFont(new Font(codeType[randomNum[i]], Font.BOLD, 30));
            g.setColor(new Color(i*60, i*45, i*32));
            g.drawLine(randomNum[i]*7, randomNum[i]*15, randomNum[i]*160,randomNum[i]*130);
            
            g.drawString(code[randomNum[i]], 10+i*30, 30);
            lastCode.append(code[randomNum[i]]);
        }
        g.drawRect(0, 0, 149, 69);
        try {
            ImageIO.write(bi, "JPEG", new FileOutputStream("F:/a.jpg"));
            
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    //生成随机数
    private static int[] getRandomNum(int num) {
        int RandomNum[] = new int[num];
        for(int i=0;i<num;i++) {
            int OnlyrandomNum = (int) (Math.random()*10);
            RandomNum[i] = OnlyrandomNum;
        }
        return RandomNum;
    }
    

//此部分用来给servlet来获得bufferedimage
    public static BufferedImage getIdentifyCodeImage() {
        ShowPicture sp = new ShowPicture();
        sp.produceIdentifyCodeImage();
        File file = new File("F:/a.jpg");
        BufferedImage image = null;
        try {
            image = ImageIO.read(file);
            
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        
        return image;
    }
    



    //此部分用在servlet中将BufferedImage输出到response.getOutputStream()
    public void out(BufferedImage bi,OutputStream os) {
        
        try {
            ImageIO.write(bi, "JPEG", os);
        } catch (IOException e) {
            e.printStackTrace();
        }
        
    }

验证码图片如下:

第二步:

已经可以生成随机验证码图片那么这一步就将随机验证码返发送到登陆页面或者你需要的页面了

先写出一个servlet(表名验证码需要请求的路径)

@WebServlet("/VerifyCode")
public class VerifyCode extends HttpServlet {


	/**
	 * 此Servlet处理来之Login.jsp的验证码请求
	 * 把生成的图片输出流输入到response流中
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ShowPicture sp = new ShowPicture();
		//得到图片bufferImage对象
		BufferedImage bi = sp.getIdentifyCodeImage();
		//得到验证码字符串
		String vcode = sp.getLastCode().toString();
		
		//输出图片,通过response将图片的流输出到请求的页面中去
		sp.out(bi, response.getOutputStream());
        //这里输出的就是每次请求的验证码(用于后期大家用来作为与用户填写的验证码比较)
		System.out.println(vcode);
	}
}

第三步:

就是写一个jsp页面将验证码图片显示出来

我这里也随便写了换一张的功能,换一张之后,在第二步中得到的验证码就是最新的验证码,大家不用担心

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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>
</head>

<script type="text/javascript">
	var i=0;
    function change() {
    	
		var v = document.getElementById("img");
		//这里如果需要黄一张只要重新请求一尺生成验证码的servlet即可
		//这里只要将请求的路径每次都不一样即可
		//这里的意思就是求情的路径不发生改变,我只是改变没吃请求的参数即?之后的部分
		//大家也可以改其他的,但是请求的路径不能错
		v.src = "/day02_2/VerifyCode?use="+(i++);
	}

</script>

<body>
	<%-- 验证码 --%>
	<img  id="img" src="${pageContext.request.contextPath }/VerifyCode">
	<!-- 按下超链接进入js操作将img的请求路径重新改变发送一次 -->
	<a href="javascript:change()">换一张</a>
</body>
</html>

第四步:

查看:登陆jsp页面

控制台输出的验证码

 

按下换一张功能:

控制台效果:

上面的代码就是源码,但是大家需要根据自己的javaweb项目更改一些项目名。

 

 

 

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以为你提供以下步骤: 1. 创建一个 HTML 文件,添加一个表单元素以获取用户输入和一个图像元素以显示验证图片。 2. 在后端使用任何编程语言(如 Python、PHP、Java 等)生成验证图片。 3. 将生成的验证图片存储到服务器上,传递给前端以显示。 4. 在用户提交表单时,将用户输入的验证码与生成的验证码进行比较,以验证用户是否是人类而不是机器人。 以下是一个示例 HTML 文件: ```html <!DOCTYPE html> <html> <head> <title>登录</title> </head> <body> <h1>登录</h1> <form method="post" action="login.php"> <label for="username">用户名:</label> <input type="text" name="username" id="username"><br><br> <label for="password">密码:</label> <input type="password" name="password" id="password"><br><br> <label for="captcha">验证码:</label> <input type="text" name="captcha" id="captcha"><br><br> <img src="captcha.php" alt="验证码"><br><br> <input type="submit" value="登录"> </form> </body> </html> ``` 在上面的示例中,我们添加了一个 `img` 标签来显示验证图片,并将其源指向 `captcha.php`。在我们的后端代码中,我们将使用 PHP 生成验证图片。以下是 PHP 代码示例: ```php <?php session_start(); $width = 100; $height = 30; $characters = 4; $possibleChars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; $randomString = ''; for ($i = 0; $i < $characters; $i++) { $randomString .= $possibleChars[rand(0, strlen($possibleChars) - 1)]; } $_SESSION['captcha'] = $randomString; $image = imagecreatetruecolor($width, $height); $backgroundColor = imagecolorallocate($image, 255, 255, 255); $textColor = imagecolorallocate($image, 0, 0, 0); imagefilledrectangle($image, 0, 0, $width, $height, $backgroundColor); $font = 'arial.ttf'; $fontSize = 16; $textbox = imagettfbbox($fontSize, 0, $font, $randomString); $x = ($width - $textbox[4]) / 2; $y = ($height - $textbox[5]) / 2; imagettftext($image, $fontSize, 0, $x, $y, $textColor, $font, $randomString); header('Content-Type: image/png'); imagepng($image); imagedestroy($image); ?> ``` 在上面的示例中,我们将生成一个随机的字符串并将其存储在会话中,然后使用 PHP 的 `imagettftext` 函数将其绘制到图像上。最后,我们将图像作为 PNG 发送到前端,以供用户查看。 当用户提交表单时,我们将检查用户输入的验证码是否与会话中存储的验证码匹配。以下是 PHP 代码示例: ```php <?php session_start(); if ($_POST['captcha'] == $_SESSION['captcha']) { // 验证码匹配 } else { // 验证码不匹配 } ?> ``` 希望这可以帮助你创建一个验证码登录页面
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值