图片验证码的实现

 现在网站上为了防止有人恶意使用程序发送垃圾信息,使用图片验证码对其进行防范。
今天试着也写了一下:
Servlet:
package cn.edu.bzu;

import java.awt.Color;
import java.awt.Font;
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.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class GetKey extends HttpServlet {
	//定义可选择的字符
	public static final char[] CHARS={'2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','J','K','L','M','N','P','Q','R','S','T','U','V','W','X','Y','Z'};
	static Random random=new Random();
	
	public String getRandomString(){
		StringBuffer buffer=new StringBuffer();
		for(int i=0;i<6;i++){	//生成六个字符
			buffer.append(CHARS[random.nextInt(CHARS.length)]);
		}
		return buffer.toString();
	}
	
	public static Color getRandomColor(){		//得到随机颜色
		return new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255));		
	}
	
	public static Color getReverseColor(Color c){	//得到颜色的反色
		return new Color(255-c.getRed(),255-c.getGreen(),255-c.getBlue());
	}
	
	public void doGet (HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException{
		response.setContentType("image/jpeg");		//设置输出类型
		String randomString=getRandomString();
		//将getSession()设置为true,当会话不存在是返回null
		request.getSession(true).setAttribute("randomString",randomString);
		
		//设置图片的宽、高
		int width=100;
		int height=30;
		
		Color bcolor=getRandomColor();	//前景色
		Color fcolor=getReverseColor(getRandomColor());	//设置背景色
		
		//创建一个彩色图片
		BufferedImage bimage=new BufferedImage(width,height,BufferedImage.TYPE_INT_BGR);
		//创建绘图对象
		Graphics2D g=bimage.createGraphics();
		//字体样式为宋体,加粗,20磅
		g.setFont(new Font("宋体",Font.BOLD,20));
		//先画出背景色
		g.setColor(bcolor);
		g.fillRect(0,0,width,height);
		//再画出前景色
		g.setColor(fcolor);
		//绘制随机字符
		g.drawString(randomString, 20,22);
		//画出干扰点
		for(int i=0,n=random.nextInt(100);i<n;i++){
			g.drawRect(random.nextInt(width), random.nextInt(height),1, 1);
		}
		
		ServletOutputStream outstream=response.getOutputStream();
		JPEGImageEncoder encoder=JPEGCodec.createJPEGEncoder(outstream);
		
		encoder.encode(bimage);
		outstream.flush();


	}
}

前台JSP页面:
<%@ page language="java" contentType="text/html;charset=utf-8" %>
<%@ page import="cn.edu.bzu.GetKey" %>
<jsp:useBean id="show" scope="page" class="cn.edu.bzu.GetKey"/>
<html>
	<head><title>登陆</title>
	<script language="javascript" type="text/javascript">
		function changeImage(){
			document.getElementById("ch").disabled=true;
			document.getElementById("imc").src="http://localhost:8080/ExerciseTest/GetKey?ts="+new Date().getTime();
		}
	</script>
	</head>
	<body>
	<form action="GoTest" method="get">
		<table width="400" height="200" border="1" borderColor="blue">
			<tr>
			  <td colspan="4" align="center">
				后台登陆
			   </td>
			</tr>
			<tr>
			 <td>用户名:</td>
			 <td colspan="3"><input type="text" name="username" style="width:200px;height:30px;font-family:微软雅黑"/></td>
			</tr>
			<tr>
			  <td>
			    密  码:
			  </td>
			  <td colspan="3">
			  <input type="password" name="pass" style="width:200px;height:30px;"/>
			  </td>
			</tr>
			 <tr>
			   <td>
			    验证码:
			   </td>
			   <td>
			    <input type="text" name="checkkey" style="width:80px;height:30px;padding-top:4px;"/>
			   </td>
			   <td>
			   <img src="http://localhost:8080/ExerciseTest/GetKey" id="imc" οnlοad="ch.disabled=false;"/>
			   </td>
			   <td>
			  <a href="javascript:οnclick=changeImage()" id="ch">看不清,换一张</a>
			   </td>
			 </tr>
			<tr>
			  <td align="center" style="width:400px;" colspan="4">
			  	<input type="submit" value="提     交"/>
			  	<input type="reset" value="重     置"/>
			  </td>
			</tr>
		</table>
		</form>
	</body>
	
</html>

JSP页面效果:










只是简单的处理了一下。





在上面的servlet中可以得到验证码的相关信息的……
可以通过request.getSession().getAttribute("randomString");得到验证码。
……
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
在 Spring Boot 中实现图片验证码可以通过以下步骤进行: 1. 添加依赖:在 `pom.xml` 文件中添加以下依赖项: ```xml <dependency> <groupId>com.github.axet</groupId> <artifactId>kaptcha</artifactId> <version>0.0.9</version> </dependency> ``` 2. 创建验证码生成器:创建一个验证码生成器类,用于生成验证码图片。可以参考以下示例代码: ```java import com.google.code.kaptcha.impl.DefaultKaptcha; import com.google.code.kaptcha.util.Config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.Properties; @Configuration public class CaptchaConfig { @Bean public DefaultKaptcha defaultKaptcha() { DefaultKaptcha defaultKaptcha = new DefaultKaptcha(); Properties properties = new Properties(); properties.setProperty("kaptcha.border", "no"); properties.setProperty("kaptcha.textproducer.font.color", "black"); properties.setProperty("kaptcha.image.width", "150"); properties.setProperty("kaptcha.image.height", "50"); properties.setProperty("kaptcha.textproducer.char.length", "4"); Config config = new Config(properties); defaultKaptcha.setConfig(config); return defaultKaptcha; } } ``` 3. 创建验证码接口:创建一个接口或控制器,用于处理验证码相关的请求,并将生成的验证码图片返回给前端。示例代码如下: ```java import com.google.code.kaptcha.impl.DefaultKaptcha; import com.google.code.kaptcha.util.Config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import javax.imageio.ImageIO; import javax.servlet.http.HttpServletResponse; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.OutputStream; @RestController public class CaptchaController { private final DefaultKaptcha captchaGenerator; @Autowired public CaptchaController(DefaultKaptcha captchaGenerator) { this.captchaGenerator = captchaGenerator; } @GetMapping("/captcha") public void getCaptcha(HttpServletResponse response) throws IOException { // 生成验证码 String captchaText = captchaGenerator.createText(); BufferedImage captchaImage = captchaGenerator.createImage(captchaText); // 将验证码文本存储在 session 中(可根据具体需求存储在其他地方) // request.getSession().setAttribute("captcha", captchaText); // 将验证码图片输出给前端 response.setContentType("image/jpeg"); try (OutputStream outputStream = response.getOutputStream()) { ImageIO.write(captchaImage, "jpeg", outputStream); outputStream.flush(); } } } ``` 4. 前端页面:在前端页面中使用 `<img>` 标签来显示验证码图片,并添加一个刷新按钮。示例代码如下: ```html <!DOCTYPE html> <html> <head> <title>Captcha Demo</title> </head> <body> <h1>Captcha Demo</h1> <img id="captchaImage" src="" alt="Captcha"> <button onclick="refreshCaptcha()">Refresh</button> <script> function refreshCaptcha() { var captchaImage = document.getElementById("captchaImage"); captchaImage.src = "/captcha?t=" + new Date().getTime(); } // 页面加载时刷新验证码 window.onload = function() { refreshCaptcha(); }; </script> </body> </html> ``` 这样就可以在 Spring Boot 中实现图片验证码了。用户可以通过访问 `/captcha` 路径获取验证码图片,并在前端页面中显示。每次刷新验证码时,可以调用 `refreshCaptcha()` 函数来更新验证码图片。请根据自己的需求进行相应的调整和扩展。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值