3_32江_0409—javaweb验证码干扰线
引言
首先,通过上节课的学习,我们模拟了登录页面的简易密码判断,今天我们来实现简单的验证码语句实现:
1、重新创建一个java类
我们在之前的源根目录下继续新建一个Java类叫做CaptcheController,并继承于HttpServlet ,重写service,设置映射关系/captche,代码如下:
package cn.edu.mju.project13.controller;
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 javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
@WebServlet("/captche")
public class CaptcheController extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.service(req, resp);
}
}
2、编写service和BufferedImage generatePic函数
我们对两个函数进行编写(部分内容已经给出标注信息),代码如下:
import java.util.Random;
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletOutputStream sos = resp.getOutputStream();
ImageIO.write(generatePic(100,80),"JPEG",sos);
sos.flush();
sos.close();
}
private BufferedImage generatePic(int width,int height){
Random rnd = new Random(); //设置随机数
BufferedImage image = new BufferedImage(100,80,BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
g.setColor(Color.WHITE);
g.fillRect(0,0,width,height);
g.setColor(Color.BLACK);
g.setFont(new Font("宋体",Font.BOLD,20));
g.drawString("1234",10,20); //简单的验证码内容
for(int j=0,n=rnd.nextInt(100);j<n;j++){ //设置随机点
g.setColor(Color.RED);
g.fillRect(rnd.nextInt(width),rnd.nextInt(height),1,1);
}
for (int i=0;i<5;i++){
g.setColor(new Color(rnd.nextInt(255),rnd.nextInt(255), rnd.nextInt(255)));
int x1=rnd.nextInt(90);
int y1=rnd.nextInt(30);
int x2=rnd.nextInt(90);
int y2=rnd.nextInt(30);
g.drawLine(x1,y1,x2,y2);
}
g.dispose();
return image;
}
3、验证效果
现在我们进行验证成果,假设现在我们的patch=/Project13(上下文),端口为8081,映射为/captche,我们进行localhost(本机地址127.0.0.1)运行代码使用HTTP超文本传输协议访问页面,显示一个验证码内容为1234的简单验证码图片: