我是灼灼,一只初学Java的大一金渐层。
向往余秀华和狄兰·托马斯的疯狂,时常沉溺于将情感以诗相寄;追逐过王尔德、王小波的文字,后陷于毛姆和斯蒂芬·金不可自拔;热爱文学的浪潮,白日梦到底却总在现实里清醒;艳羡平静又极度渴盼奔跑的力量。
欢迎与我交流鸭· QQ:1517526827;
个人博客:https://blog.csdn.net/weixin_52777510?spm=1001.2101.3001.5343
项目login时的图形验证码实现
转载自学长的博客,所有源代码均来自学长的博客。
让我们研究一下!嘿嘿~
以下是全部内容:
图形验证码
使用Java,jsp,servlet来实现图形验证码的功能(这么看来我是一定要学jsp的了!)——
要实现验证码的功能,首先要知道验证码的实现原理,其实就是在项目中创建一个画笔,画板,然后利用方法来实现画笔在画板上**“画”出验证码的内容,最后将在画布上形成的内容以图片**的方式放出。
也就是说,实现验证码一共分为一下5个部分:
1.创建画板:new BufferedImage();
2.创建画笔:画板.getGraphics();
3.生成随机内容:不同颜色的字符;
4.绘制内容:画笔.drawString();
5.存为图片发送:ImageIO.write()(画板,图片类型,输出流);
开始编写项目:
首先,建立一个新的web项目,并在web文件下新建一个jsp页面(这个页面用来设计网页页面,并接受所创建的验证码图片)。然后编写jsp页面的代码,如下:
<%
//实现随机字符串验证码
String path = request.getContextPath();
String basePath = request.getScheme()+"";
%>
<html>
<head>
<base href="<%=basePath%>">
<title>实现随机验证码</title>
<style type="text/css">/*设置样式*/
.code_a{
color: #0000ff;/*颜色*/
font-size:12px;/*字体大小*/
text-decoration: none;/*有无下划线*/
cursor: pointer;/*鼠标样式*/
}
#imgCode{
cursor: pointer;/*鼠标样式*/
}
</style>
/*写脚本*/
<script type="text/javascript">
function changeCode(){
//实现更换验证码的功能
var imgCode = document.getElementById("imgCode");
imgCode.src="abc?"+Math.random();//这是为了换一张验证码图片,因为如果="abc"的话,由于每次的内容都是一样的,是不会进行更换的,所以在后面加了一个随机数。
}
</script>
</head>
<body>
<form action="code1" method="post">
<label>验证码:</label>
<input type="text" id="inCode" name="inCode"/><br>
<img src="code21" align="center" id="imgCode"
onclick="changeCode()"/>//code21是设置的servlet的路径
<a class="code_a" onclick="changeCode()">换一张</a><br>//超链接引用changeCode功能实现换一张功能。
<input type="submit" value="登录" />//提交输入的验证码
</form>
<div style="color: red;">${err}</div>//错误设置区域
</body>
</html>
在页面设计好后,开始编写servlet了,在servlet中要做的就是上文所提到的5个步骤:
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Collections;
import java.util.Random;
//引用的类
@WebServlet(name = "NewCode",urlPatterns = "/code1")
//这个相当于在xml文件中对servlet进行了**注册**,name是名字,urlPatterns是设置的**访问路径**,在这里设置的路径是与上面的**img中的一致**的
public class NewCode extends HttpServlet {
private Random random = new Random();//生成随机数字
private int width = 80;//宽度
private int height = 30;//高度
private int fontsize = 12;//字体大小
private String str = "0123456789abcdef";
//生成四个字符的随机字符串
private String randCode(int len){
if(len<4){
len = 4;
}
//更改图片宽度
width = 5+ fontsize*len;
//生成字符串
String code = "";
for (int i = 0; i < len; i++) {
code += str.charAt(random.nextInt(str.length()));//依次返回指定索引处的字符
}
return code;
}
//返回随机颜色
private Color randColor(){
int r = random.nextInt(256);
int g = random.nextInt(256);
int b = random.nextInt(256);
return new Color(r,g,b);//r,g,b分别是红,绿,蓝的首字母缩写
}
**protected** void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//参数是请求和回应
// 1.创建画板
BufferedImage img = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
//后面的三个参数分别是宽高和颜色
// 2.创建画笔
Graphics2D pen = (Graphics2D)img.getGraphics();//由于getGraphics所返回的是一个getGraphics对象,所以需要将其转换成Graphics2D
// 3.生成随机内容
String code = randCode(4);
request.getSession().setAttribute("valiCode",code);//session要学习一下
// 4.绘制内容
// 4.1 设置绘制区域
pen.fillRect(0,0,width,height);
// 4.2 设置字体
pen.setFont(new Font("微软雅黑",Font.BOLD,fontsize));
// 4.3 按顺序逐个绘制字符
for (int i = 0; i < code.length(); i++) {
pen.setColor(randColor());
//绘制字符
pen.drawString(code.charAt(i)+"",5+i*fontsize,(fontsize+height)/2);
}
// 4.4 绘制干扰线
for (int i =0; i<2;i++){
pen.setColor(randColor());
pen.setStroke(new BasicStroke(1));
//设置干扰线的高度,宽度
pen.drawLine(random.nextInt(width/2),random.nextInt(height),random.nextInt(width),random.nextInt(height));
}
// 5.存为图片并发送
ServletOutputStream out = response.getOutputStream();
ImageIO.write(img,"png",out);
out.flush();
out.close();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(传参);//令doGet做doPost
}
最后是实现数据的检验,也就是将用户输入的数据与后台产生的数据进行对比,如果数据一致,那么就成功,如果数据有误,那就返回一个错误信息。
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(name = "ValiCode",urlPatterns = "/code21")
public class ValiCode extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.得到数据
String inCode = request.getParameter("inCode").toString().toLowerCase();//通过request中的方法获得用户输入的数据,getParameter方法!
String valiCode = request.getSession().getAttribute("valiCode").toString().toLowerCase();
//通过getSession方法得到由程序产生的验证码,getSession方法
//2.验证是否正确
if (inCode.equals(valiCode)){
response.sendRedirect("index.jsp");//验证码正确,**跳转**到一个页面
}else {
request.getSession().setAttribute("err","验证码输入错误,请重新输入!");
//返回上一页
String url = request.getHeader("Referer");
response.sendRedirect(url);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}
所有的内容就是这些了,距离把这个学会可能还需要先学习一些session,cookie和servlet基础。
如果对你有帮助的话不要忘记一键三连噢~
谢谢鸭~
初次编写于2021/2/19日;