前段時間你們都說最近大環境很差,好多公司在裁人,換工做的話不推薦輕易的裸辭,可是我想說的是我所在的公司好流弊,有作不完的業務需求,還有就是招不完的人......
最近我也是比較繁忙,可是仍是要抽一點時間來進行自我覆盤和記錄,最近也寫一個簡單的小功能,就是登錄界面的圖片驗證碼功能javascript
環境:Tomcat九、Jdk1.8
public class RandomValidateCodeUtil { public static final String RANDOMCODEKEY= "RANDOMVALIDATECODEKEY";//放到session中的key private String randString = "0123456789";//隨機產生只有數字的字符串 private String //private String randString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";//隨機產生只有字母的字符串 //private String randString = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";//隨機產生數字與字母組合的字符串 private int width = 95;// 圖片寬 private int height = 25;// 圖片高 private int lineSize = 40;// 干擾線數量 private int stringNum = 4;// 隨機產生字符數量 private static final Logger logger = LoggerFactory.getLogger(RandomValidateCodeUtil.class); private Random random = new Random(); /** * 得到字體 */ private Font getFont() { return new Font("Fixedsys", Font.CENTER_BASELINE, 18); } /** * 得到顏色 */ private Color getRandColor(int fc, int bc) { if (fc > 255) fc = 255; if (bc > 255) bc = 255; int r = fc + random.nextInt(bc - fc - 16); int g = fc + random.nextInt(bc - fc - 14); int b = fc + random.nextInt(bc - fc - 18); return new Color(r, g, b); } /** * 生成隨機圖片 */ public void getRandcode(HttpServletRequest request, HttpServletResponse response) { HttpSession session = request.getSession(); // BufferedImage類是具備緩衝區的Image類,Image類是用於描述圖像信息的類 BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR); Graphics g = image.getGraphics();// 產生Image對象的Graphics對象,改對象能夠在圖像上進行各類繪製操做 g.fillRect(0, 0, width, height);//圖片大小 g.setFont(new Font("Times New Roman", Font.ROMAN_BASELINE, 18));//字體大小 g.setColor(getRandColor(110, 133));//字體顏色 // 繪製干擾線 for (int i = 0; i <= lineSize; i++) { drowLine(g); } // 繪製隨機字符 String randomString = ""; for (int i = 1; i <= stringNum; i++) { randomString = drowString(g, randomString, i); } logger.info(randomString); //將生成的隨機字符串保存到session中 session.removeAttribute(RANDOMCODEKEY); session.setAttribute(RANDOMCODEKEY, randomString); g.dispose(); try { // 將內存中的圖片經過流動形式輸出到客戶端 ImageIO.write(image, "JPEG", response.getOutputStream()); } catch (Exception e) { logger.error("將內存中的圖片經過流動形式輸出到客戶端失敗>>>> ", e); } } /** * 繪製字符串 */ private String drowString(Graphics g, String randomString, int i) { g.setFont(getFont()); g.setColor(new Color(random.nextInt(101), random.nextInt(111), random .nextInt(121))); String rand = String.valueOf(getRandomString(random.nextInt(randString .length()))); randomString += rand; g.translate(random.nextInt(3), random.nextInt(3)); g.drawString(rand, 13 * i, 16); return randomString; } /** * 繪製干擾線 */ private void drowLine(Graphics g) { int x = random.nextInt(width); int y = random.nextInt(height); int xl = random.nextInt(13); int yl = random.nextInt(15); g.drawLine(x, y, x + xl, y + yl); } /** * 獲取隨機的字符 */ public String getRandomString(int num) { return String.valueOf(randString.charAt(num)); } }
這個類不用動,能夠直接拿來用html
<!--html/bady代碼--> <div > <div > <div > <input type="tel" id="verify_input" placeholder="請輸入驗證碼" maxlength="4"> </div> </div> <div > <a href="javascript:void(0);" title="點擊更換驗證碼"> <img id="imgVerify" src="login/getVerify" alt="更換驗證碼" height="36" width="170" onclick="getVerify(this);"> </a> </div> <input type="button" onclick="aVerify()" value="提交"> </div> </body> <!--js中的代碼--> <script type="text/javascript" src="./js/jquery.min.js"></script> <script> //獲取驗證碼 /*function getVerify(obj){ obj.src = "login/getVerify?"+Math.random();//原生js方式 }*/ //獲取驗證碼 function getVerify() { // $("#imgCode").on("click", function() { $("#imgVerify").attr("src", 'login/getVerify?' + Math.random());//jquery方式 // }); } function aVerify(){ var value =$("#verify_input").val(); // alert(value); $.ajax({ async: false, type: 'post', url: 'login/checkVerify', dataType: "json", data: { verifyInput: value }, success: function (result) { if (result) { alert("success!"); } else { alert("failed!"); } // window.location.reload(); getVerify(); } }); } </script>
注意:這裏有2種獲取驗證碼圖片的方法
@RestController @RequestMapping("/login") public class Picverifyaction { private final static Logger logger = LoggerFactory.getLogger(Picverifyaction.class); /** * 生成驗證碼 */ @RequestMapping(value = "/getVerify") public void getVerify(HttpServletRequest request, HttpServletResponse response) { try { response.setContentType("image/jpeg");//設置相應類型,告訴瀏覽器輸出的內容爲圖片 response.setHeader("Pragma", "No-cache");//設置響應頭信息,告訴瀏覽器不要緩存此內容 response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expire", 0); RandomValidateCodeUtil randomValidateCode = new RandomValidateCodeUtil(); randomValidateCode.getRandcode(request, response);//輸出驗證碼圖片方法 } catch (Exception e) { logger.error("獲取驗證碼失敗>>>> ", e); } } /** * 校驗驗證碼 */ @RequestMapping(value = "/checkVerify", method = RequestMethod.POST,headers = "Accept=application/json") public boolean checkVerify(@RequestParam String verifyInput, HttpSession session) { try{ //從session中獲取隨機數 String inputStr = verifyInput; String random = (String) session.getAttribute("RANDOMVALIDATECODEKEY"); if (random == null) { return false; } if (random.equals(inputStr)) { return true; } else { return false; } }catch (Exception e){ logger.error("驗證碼校驗失敗", e); return false; } } }
固然上面代碼只是核心部分,若是有問題可去github自行下載 charmsongojava
若是有什麼更好的方法歡迎留言
參考:https://blog.csdn.net/Colton_...jquery