实现了一个图片验证码的功能,demo如图所示
怎么实现的呢?
需要写4个东西:
1.登录页面的jsp和js
2.验证码图片的实体类
3.生成验证码图片的servlet
4.处理登录请求的servlet
先看jsp代码:
一进入页面,就会生成一张验证码图片,因为写了 src="yanzheng"调用生成验证码图片的servlet;
然后点击图片会触发js方法,会重新调用生成验证码图片的servlet生成一张验证码图片;
点击登录,调用处理登录的servlet比较用户名密码和验证码是否正确。
<form class="ui form error" method="post"
action="${pageContext.request.contextPath }/user">
<div class="field">
用户名
<input autofocus="" id="id_username" maxlength="254" name="username" type="text" required />
</div>
<div class="field">
密码
<input id="id_password" name="password" type="password" required />
</div>
<div class="field">
<!-- 验证码图片 -->
<img class="verifyCode" onclick="changeCode()" src="yanzheng">
<input class="verifyInput" name="verifyInput" placeholder="请输入验证码">
</div>
<button class="ui inverted red circular right floated button" type="submit">
登录
</button>
</form>
/* 点击刷新验证码 */
function changeCode(){
var src = "http://localhost:8080/javawebchatroom/yanzheng"
$('.verifyCode').attr("src",src);
}
然后看下验证码图片的实体类
设置了一些参数,例如字体设置、内容组合、旋转角度、干扰线、噪点等
package com.vo;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.util.Random;
/*对图片进行处理的类和方法*/
public class VerifyCode {
public static String drawRandomText(int width, int height, BufferedImage verifyImg) {
Graphics2D graphics = (Graphics2D) verifyImg.getGraphics();
graphics.setColor(Color.WHITE);// 设置画笔颜色-验证码背景色
graphics.fillRect(0, 0, width, height);// 填充背景
graphics.setFont(new Font("微软雅黑", Font.BOLD, 40));
// 数字和字母的组合
String baseNumLetter = "123456789abcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ";
StringBuffer sBuffer = new StringBuffer();
int x = 10; // 旋转原点的 x 坐标
String ch = "";
Random random = new Random();
for (int i = 0; i < 4; i++) {
graphics.setColor(getRandomColor());
// 设置字体旋转角度
int degree = random.nextInt() % 30; // 角度小于30度
int dot = random.nextInt(baseNumLetter.length());
ch = baseNumLetter.charAt(dot) + "";
sBuffer.append(ch);
// 正向旋转
graphics.rotate(degree * Math.PI / 180, x, 45);
graphics.drawString(ch, x, 45);
// 反向旋转
graphics.rotate(-degree * Math.PI / 180, x, 45);
x += 48;
}
// 画干扰线
for (int i = 0; i < 6; i++) {
// 设置随机颜色
graphics.setColor(getRandomColor());
// 随机画线
graphics.drawLine(random.nextInt(width), random.nextInt(height),
random.nextInt(width), random.nextInt(height));
}
// 添加噪点
for (int i = 0; i < 30; i++) {
int x1 = random.nextInt(width);
int y1 = random.nextInt(height);
graphics.setColor(getRandomColor());
graphics.fillRect(x1, y1, 2, 2);
}
return sBuffer.toString();
}
/**
* 随机取色
*/
private static Color getRandomColor() {
Random ran = new Random();
Color color = new Color(ran.nextInt(256),
ran.nextInt(256), ran.nextInt(256));
return color;
}
}
再看生成验证码图片的servlet,以图片流的形式直接输出到前台,并将验证码内容进行了储存(此处储存在session里的,真正用的时候可以储存在redis里或者其他地方里)
package com.action;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
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;
import com.vo.VerifyCode;
@WebServlet("/YanzhengServlet")
public class YanzhengServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public YanzhengServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
/**
* 验证码
*/
try {
System.out.println("验证码");
int width = 200;
int height = 69;
BufferedImage verifyImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// 生成对应宽高的不带透明色初始图片
String randomText = VerifyCode.drawRandomText(width, height, verifyImg);
// 单独的一个类方法,出于代码复用考虑,进行了封装。
// 功能是生成验证码字符并加上噪点,干扰线,返回值为验证码字符
request.getSession().setAttribute("verifyCode", randomText);
response.setContentType("image/png");// 必须设置响应内容类型为图片,否则前台不识别
OutputStream os = response.getOutputStream(); // 获取文件输出流
ImageIO.write(verifyImg, "png", os);// 输出图片流
os.flush();
os.close();// 关闭流
} catch (IOException e) {
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
然后就是UserServlet处理登录请求了,比较用户名密码和验证码对不对。我们就贴下验证码比较的就行了。
public String login(HttpServletRequest req,HttpServletResponse resp){
// 接收数据
String inputcode = req.getParameter("verifyInput");
String code = (String) req.getSession().getAttribute("verifyCode");
try {
if(!(inputcode.equals(code))){
req.setAttribute("error", "验证码错误!");
return "/login.jsp";
}
return null;
}
至此,验证码图片就实现了,还是比较简单的。
之后有时间出个短信验证码注册或登录的吧,这个需要去阿里云申请下短信接口噢。
---------------------------------------