在登录页面加入随机生成的验证码验证登录
1.前端页面,在点击验证码时发送请求,获得随机验证码
<ul> <li class="user_main_text">验证码: </li> <li class="user_main_input"> <img id="img" src="/getyanzheng" onclick="b()" alt=""> <input type="text" name="yanzheng"/></li> </ul>
<script type="text/javascript"> function b() { document.getElementById("img").src="/getyanzheng?num="+Math.random();
</script>
2.编写ImageUtil工具类
import java.awt.*; import java.awt.image.BufferedImage; import java.util.Random; public class ImageUtil { //1.定义变量保存生成后的验证码字符串 static String code = ""; //2.生成验证码 public static String createcode() { code = ""; String a = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; for (int i = 0; i < 4; i++) { int index = (int) (Math.random() * 62); char b = a.charAt(index); code = code + b; } return code; } //查看已经生成的验证码 public static String getCode() { return code; } //3.生成图片 public static BufferedImage createimage() { BufferedImage bi = new BufferedImage(70, 30, BufferedImage.TYPE_INT_RGB); //1.得到一个画布 Graphics g = bi.getGraphics(); //2.添加背景颜色 g.setColor(Color.ORANGE); g.fillRect(0, 0, 70, 30); //3.添加干扰线 for (int i = 0; i < 30; i++) { Random r = new Random(); int red = r.nextInt(256); int green = r.nextInt(256); int blue = r.nextInt(256); Color c = new Color(red, green, blue); g.setColor(c); int x1 = r.nextInt(71); int y1 = r.nextInt(31); int x2 = r.nextInt(71); int y2 = r.nextInt(31); //g.drawLine(x1,y1,x2,y2); g.drawOval(x1, y1, x2, y2); } //3.添加文字 g.setColor(Color.BLACK); g.setFont(new Font("宋体", Font.BOLD, 25)); String str = getCode(); //4.将文字填充到画板中 g.drawString(str, 10, 25); //5.关闭画布 g.dispose(); return bi; } }
3.在Controller层处理请求
package com.ly.controller; import com.ly.util.ImageUtil; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import javax.imageio.ImageIO; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletResponse; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.IOException; @Controller public class ImageController { @RequestMapping("/getyanzheng") public void yanzheng(HttpServletResponse response){ try { ImageUtil.createcode(); BufferedImage image = ImageUtil.createimage(); //以流的方式返回给客户端 response.setContentType("image/jpeg"); ByteArrayOutputStream bt = new ByteArrayOutputStream(); //将图片转换成字节流 ImageIO.write(image,"jpeg",bt); //得到输出流,返回客户端 ServletOutputStream outputStream = response.getOutputStream(); outputStream.write(bt.toByteArray()); } catch (IOException e) { e.printStackTrace(); } } }