JavaWEB/JSP 中簡單的驗證碼 springMVC

   


     

  •         spring MVC下簡單的驗證碼源碼。web


  •                 @Controller  // 註解問控制器spring

  •                 @RequestMapping("/login") // 訪問路徑session

  •                 public class GetCodeController {app

  •                 @RequestMapping("/getCode")dom

  •                 public void execute(HttpServletResponse response, ide

  •             HttpSession session)throws Exception {ui

  •                                      BufferedImage p_w_picpath = new BufferedImage(100, 30,BufferedImage.TYPE_INT_RGB);spa


  •                 Graphics g = p_w_picpath.getGraphics();code

  •                 Random r = new Random();             
    ci


  •                 g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));

  •               

  •                 g.fillRect(0, 0, 100, 30);

  •                 String number = getNumber(5);

  •                 session.setAttribute("scode", number);

  •                 g.setColor(new Color(0, 0, 0));

  •                 g.setFont(new Font(null, Font.BOLD, 24));

  •                 g.drawString(number, 5, 25);

  •               

  •                 for (int i = 0; i < 8; i++) {

  •                 g.setColor(new Color(r.nextInt(255), r.nextInt(255),

                r.nextInt(255), r.nextInt(255)));

                    g.drawLine(r.nextInt(100), r.nextInt(30), 

r.nextInt(100), r.nextInt(30));

                }                response.setContentType("p_w_picpath/jpeg");                 OutputStream ops = response.getOutputStream();                ImageIO.write(p_w_picpath, "jpeg", ops);                 ops.close();                }          
  •                 private String getNumber(int size) {

  •                 String str = 

        "ABCDEFGHIJKLMNOPQRSTUVWXYZqwertyuiopasdfghjklzxcvnm0123456789";

                String number = "";                Random r = new Random();                for (int i = 0; i < size; i++) {                number += str.charAt(r.nextInt(str.length())); }                return number;                }

        }


        

        驗證碼是咱們在web開發中常常要用的的一個組件,特別是在請求分發中利用控制器

    來獲取驗證碼,便於維護並且高大上。 

相關文章
相關標籤/搜索