• java代码生成随机验证码


    1.  新建一个controller

    @Controller
    @RequestMapping("/index")
    public class LoginController {
    
    	@RequestMapping("/logins")
    	public void login(HttpServletRequest request, HttpServletResponse response) throws IOException {
    
    		int width=100;
    		int height=50;
    		//创建一个对象,在内存中图片(验证码图片对象)
    		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    
    		//美化图片
    		//填充背景色
    		Graphics graphics = image.getGraphics();
    		graphics.setColor(Color.green);
    		Font font = new Font("黑体",Font.PLAIN,20);
    		graphics.setFont(font);
    		graphics.fillRect(0,0,width,height);
    
    		//画边框
    		graphics.setColor(Color.black);
    		graphics.drawRect(0,0,width-1,height-1);
    
    		String str="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    
    		Random random = new Random();
    
    		for (int i = 0; i < 4; i++) {
    			int index = random.nextInt(str.length());
    			//随机字符
    			char charAt = str.charAt(index);
    			//写验证码
    			graphics.drawString(charAt+"",width/5*i,height/2);
    		}
    		//画干扰线
    		graphics.setColor(Color.GREEN);
    		//随机生成坐标点
    		for (int i = 0; i < 10; i++) {
    			int x1=random.nextInt(width);
    			int x2= random.nextInt(width);
    
    			int y1=random.nextInt(height);
    			int y2=random.nextInt(height);
    			graphics.drawLine(x1,y1,x2,y2);
    
    			//将图片输出到页面上
    			ImageIO.write(image,"jpg",response.getOutputStream());
    		}
    	}
    }
    

    2.在resources/static目录下新建一个html文件

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <title>登录</title>
    
      <script>
        window.onload = function () {
          document.getElementById("img").onclick = function () {
            this.src = "/index/logins?time=" + new Date().getTime();
          }
        }
      </script>
    
    </head>
    <body>
    <form action="/index/logins" method="post">
      <table>
        <tr>
          <td>用户名</td>
          <td><input type="text" name="username"></td>
        </tr>
    
        <tr>
          <td>密码</td>
          <td><input type="password" name="password"></td>
        </tr>
    
        <tr>
          <td>验证码</td>
          <td><input type="text" name="checkCode"></td>
        </tr>
    
        <tr>
          <td colspan="2"><img id="img" src="/index/logins"></td>
        </tr>
    
        <tr>
          <td colspan="2"><input type="submit" value="登录"></td>
        </tr>
      </table>
    </form>
    
    </body>
    </html>
    

    3.此项目的端口为8084,所以访问地址http://localhost:8084/login.html
    在这里插入图片描述

  • 相关阅读:
    新收入准则下的通用收入处理场景
    如果不先提出最佳问题,你怎么去找最佳答案呢?
    复星集团
    CFO的三重境界:阿里CFO蔡崇信教给我的那些事儿
    《让财务助推业务—业财融合》
    一、原材料、半成品、成品的采用标准成本法管理 [转发]
    顶级投行?IT->Data Analysis->Forecast->Future.
    SAP 合资公司解决方案
    SAP-关于分类账(Ledgers)的总结
    百度网盘目录树在线V2.0版功能介绍~
  • 原文地址:https://www.cnblogs.com/wgty/p/12810460.html
Copyright © 2020-2023  润新知