一个简单的登录页面除了登录账号,密码,按钮等这些,想要显得复杂一些可以做一个验证码,防止机器人登录。
下面开始做一个验证码
1,新建一个class文件。
2,编写随机生成字符的方法
public static String randString(int count){ //count 生成字符的个数
StringBuilder builder=new StringBuilder();
String str="0123456789abcdefghijklnmpqrstuvwxy";
Random rnd= new Random();
for(int i=0;i<count;i++) {
int pos = rnd.nextInt(str.length()); //从str 中生成一个随机数
String s = str.substring(pos, pos + 1);
builder.append(s);
}
return builder.toString();
}
3,在CaptcheController文件中新建一个类,具体实现验证码的图片,主要用两个方法。还有更多的验证码编写的方法可以自己尝试。
public class CaptcheController extends HttpServlet{
private final int WIDTH=100;
private final int HEIGHT=20;
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
BufferedImage img= new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_RGB); //申请内存空间,定义图片大小格式
Graphics g= img.getGraphics(); //定义画笔对象,
g.setColor(Color.blue); //调用对象的方法,定义初始颜色
g.fillRect(0,0,WIDTH,HEIGHT); //定义图片大小
Font font= new Font("Algerian", Font.ITALIC, 18); //字体设置,大小,字体,
g.setFont(font); //调用字体
g.setColor(Color.orange); // 设置字符颜色
String code= StrUtil.randString(4);
HttpSession session=req.getSession(); //用session方式来储存密码
session.setAttribute("code",code); //将随机生成的验证码 code,放到session
g.drawString(code,30,15); //显示字体位置
g.setColor(Color.black); //生成随机线
for (int i=0; i<8; i++){
Random random= new Random();
int x=random.nextInt(WIDTH);
int y=random.nextInt(HEIGHT);
int x1=random.nextInt(WIDTH);
int y1=random.nextInt(HEIGHT);
g.drawLine(x,y,x1,y1);
}
g.setColor(Color.black); //生成燥点
for (int i=0; i<100; i++){
Random random1= new Random();
int x=random1.nextInt(WIDTH);
int y=random1.nextInt(HEIGHT);
g.drawOval(x,y,1,1);
}
g.dispose();
ServletOutputStream out = resp.getOutputStream(); //定义输出流
ImageIO.write(img,"jpg",out); //图片是名字,格式是jpg,输出到out
try { //获取出现的异常
out.flush(); //缓冲图片大小
}finally{ //只执行下面的关闭
out.close(); //关闭 write方法
}
}
}
4,在登录界面获取验证码图片即可
String saveCode=(String) req.getSession().getAttribute("code"); //session 里有生成的验证码code,用getAttribute取出来
现在一个验证码的图片就可以显示出来了,图片的大小,字符的格式,还可以更改,(审美问题,图不好看,多多担待)