前言
本实验时去实现带图片验证码的登录功能。该功能分为:
- 后端生成验证码图片
- 前端显示验证码图片
服务器端
服务器端使用的是传统的servlet技术。后端通过Graphics2D去绘制图片,然后通过响应的输出流返回给前端
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
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;
@WebServlet("/RandomCodeServlet")
public class RandomCodeServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//设置一数组存放随机码
List<Integer> validCode=new ArrayList<Integer>();
//定义一个带缓冲的字符串,用于存放转换为字符床的随机码validCode
StringBuffer code=new StringBuffer();
//定义一个颜色集数组
Color[] color=new Color[]{Color.BLACK,Color.BLUE,Color.YELLOW,Color.CYAN,Color.PINK,Color.GRAY,Color.RED,Color.GREEN};
//创建一个随机数变量
Random random=new Random();
//创建一张张片(默认为黑色)
BufferedImage image = new BufferedImage(80, 45, BufferedImage.TYPE_INT_BGR);
//为照片创建绘图
Graphics2D graphics = image.createGraphics();
//设置绘图颜色
graphics.setColor(Color.white);
//将下列大小区域设置成白色
graphics.fillRect(2, 2, 76, 41);
//随机出验证码,存到validCode中
for(int n=0;n<4;n++) {
int randomMath=random.nextInt(10);
code.append(randomMath);
validCode.add(randomMath);
}
//在绘图中画出随机码,与横线
for(int n=0;n<validCode.size();n++) {
//设置字体
graphics.setFont(new Font("雅黑", Font.ITALIC|Font.BOLD, 20));
//设置颜色
graphics.setColor(color[random.nextInt(color.length-1)]);
//画出字符
graphics.drawString(validCode.get(n)+"", 20*n+3, 30+(random.nextInt(17)-8));
graphics.setColor(color[random.nextInt(color.length-1)]);
//画出横线,随机位置
graphics.drawLine(random.nextInt(image.getWidth()+1), random.nextInt(image.getHeight()+1), random.nextInt(image.getWidth()+1), random.nextInt(image.getHeight()+1));
//再次设置颜色
graphics.setColor(color[random.nextInt(color.length-1)]);
//画出横线,随机位置,每次循环画两次,总共8条横线
graphics.drawLine(random.nextInt(image.getWidth()+1), random.nextInt(image.getHeight()+1), random.nextInt(image.getWidth()+1), random.nextInt(image.getHeight()+1));
}
//System.out.println(code);
//获得一字节输出流
ServletOutputStream out = resp.getOutputStream();
//使用ImageIO,将照片以jpg的格式通过out发送给客户端
ImageIO.write(image, "jpg", out);
}
}
前端客户端
客户端使用了JSTL标签库,与jQuery的ajax方法。所以需要导入:
- <%@ taglib prefix=“c” uri=“http://java.sun.com/jstl/core_rt”%>
- < script type=“text/javascript” src=“jquery-min.js”>< /script>
注:jquery-min.js需要自己独立去下载
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt"%>
<!DOCTYPE HTML>
<html>
<head>
<title>博主登录</title>
<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0;" name="viewport" />
<script type="text/javascript" src="js/jquery-min.js"></script>
<script type="text/javascript">
<!--该方法在加载完毕时调用,为class为codeimg的标签添加一个点击事件,当其点击时执行ajax方法。将通过get方法传给服务端的RandomCodeServlet,当请求成功时,改变class为codeimg的标签的src-->
$(document).ready(function() {
$('.codeimg').click(function() {
$.ajax({
url : 'RandomCodeServlet',
type: 'get',
success : function(data, status, xhr) {
$('.codeimg').attr('src', 'RandomCodeServlet');
},
});
});
});
</script>
<style type="text/css">
body {
text-align: center;
height: 100%;
}
.bgImg {
position: absolute;
top: 0px;
left: 0px;
bottom: 0px;
right: 0px;
width: 100%;
height: 100%;
}
.logo {
width: 800px;
}
.bidTitle {
color: #e6e6e6;
font-size: 34px;
font-weight: 600;
}
.logCon {
color: #FFFFFF;
margin-top: 40px;
}
.line {
}
.content {
width: 42%;
position: fixed;
background: #838B8B;
left: 29%;
padding: 5% 1%;
margin-top: 12%;
border-radius: 5px;
}
.logingBut {
background: #2E8B57;
border: none;
padding: 12px 0px;
color: #edefee;
border-radius: 2px;
width: 130px;
margin-left: 30px;
margin-top: 5px;
}
.bt_input {
border-radius: 2px;
border: none;
padding: 11px 5px;
width: 280px;
margin-right: 20px;
color: #333;
margin-left: 5px;
margin-bottom: 18px;
background: #ffffffd9;
}
.bt_input_code {
border-radius: 2px;
border: none;
padding: 11px 5px;
width: 120px;
margin-right: 20px;
color: #333;
margin-left: 5px;
margin-bottom: 18px;
background: #ffffffd9;
}
.code_line {
width: 70%;
margin-left: 13%;
}
.input_code_line {
float: left;
}
.input_code {
float: right;
}
.codeimg {
width: 80px;
height: 40px;
margin-top: 4px;
}
.logCon span {
font-size: 18px;
height: 40px;
line-height: 40px;
}
</style>
</head>
<body onmousemove=/HideMenu()/ oncontextmenu="return false" ondragstart="return false" onselectstart ="return false" onselect="document.selection.empty()" oncopy="document.selection.empty()" onbeforecopy="return false" onmouseup="document.selection.empty()">
<div class="content">
<!--请自己写登录的servlet-->
<form action="#" method="get">
<div class="bidTitle">博客系统登录</div>
<div class="logCon">
<div class="line">
<span>账 号</span> <input class="bt_input"
type="text" name="name" value="lcm" />
</div>
<div class="line">
<span>密 码</span> <input class="bt_input"
type="password" name="pswd" value="123" />
</div>
<div class="line">
<span style="margin-left: -160px;">验证码</span> <input class="bt_input_code" type="text"
name="code" /> <img alt="验证码" src="RandomCodeServlet"
class="codeimg" style="position: absolute;; float: left;">
</div>
<div style="width: 100%; height: 5px; clear: both;"></div>
<input type="submit" class="logingBut" value="登录"
style="clear: both;"> <a href="regBlog.jsp"><input
type="button" class="logingBut" value="注册"></a>
</div>
</form>
</div>
</body>
</html>