1.验证码的思路
1.1一般是字母数子组成
1.2验证码是以图片的形式显示在页面
1.3如果有需求,也可以封装成工具类
//创建图片缓冲区对象BufferedImage bf = new BufferedImage(120, 46, BufferedImage.TYPE_INT_RGB);//拿到画笔对象Graphics graphics = bf.getGraphics();//绘制//设置颜色graphics.setColor(new Color(180, 90, 255));graphics.fillRect(0, 0, 166, 46);//设置大小graphics.setFont(new Font("Courier New", Font.BOLD,30));//定义绘制出来的文本内容的数据String info="qwertyuiopasdfghjklzxcvb1234567890QWERTYUIOPASDFGHJKLZXCVB";//将字符串转换成字符数组char[] charArray = info.toCharArray();//创建随机对象Random random = new Random();//定义一个字符串存储验证码的值String str="";//绘制干扰线for (int i = 0; i < 11; i++) {graphics.setColor(new Color(random.nextInt(90),random.nextInt(255),random.nextInt(180)));graphics.drawLine(random.nextInt(20), random.nextInt(60), random.nextInt(110), random.nextInt(50));}for (int i = 0; i < 4; i++) {//设置颜色graphics.setColor(new Color(random.nextInt(90),random.nextInt(255),random.nextInt(180)));//设置大小graphics.setFont(new Font("Courier New", Font.BOLD,30));int nextInt = random.nextInt(info.length());graphics.drawString(charArray[nextInt]+"", i*20+15, 40);str+=charArray[nextInt];}req.getSession().setAttribute("str",str);//通过ImageIO传输流中写的方法进行渲染到页面上ImageIO.write(bf, "jpg", resp.getOutputStream());
2.验证码的校验
2.1根据输入框输入的值和验证码里面的值比较如果相等的话验证码正确,不相等可以可以提示重现输入正确得验证码。
public String code(HttpServletRequest req, HttpServletResponse resp){//拿到输入框里的值String code = req.getParameter("code");//把存储在session里面的值取出来String attribute = (String) req.getSession().getAttribute("str");//不区分大小写判断if(code.equalsIgnoreCase(attribute)){return "r:error.jsp?msg=succ";}else{return "r.error.jsp?msg=er";}}
3.验证码的切换
3.1我用的是原生js写的 所有直接写了一个点击事件onclick并且方法名里面传了个this,this代表img本身,代码如下
<script type="text/javascript">
function changImage(img){
img.src="code?d"+new Date();
}
</script>