文章目錄
- Javaweb實現驗證碼
- 前端
- 后臺
- Springboot添加驗證碼
- 項目結構
- 依賴
- 控制類
- 前端頁面
- 效果圖
Javaweb實現驗證碼
前端
添加樣式
<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0"><title>FM_blog</title><link rel="stylesheet" type="text/css" href="res/layui/css/layui.css"><link rel="stylesheet" type="text/css" href="res/css/main.css"><script src="http://cdn.bootcss.com/jquery/1.12.3/jquery.min.js"></script><script src="layer/layer.js"></script>
編寫代碼
<div> <fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;"><legend>鋒芒博客登錄</legend></fieldset></div>
<div class="layui-container fly-marginTop"><div class="fly-panel fly-panel-user"><div class="layui-tab layui-tab-brief" ><ul class="layui-tab-title"><li class="layui-this">登入</li><li><a href="reg.jsp">注冊</a></li></ul><div class="layui-form layui-tab-content" id="LAY_ucm" style="padding: 20px 0;"><div class="layui-tab-item layui-show"><div class="layui-form layui-form-pane"><form role="form" method="POST" name="login" action="LoginServlet"><div class="layui-form-item"><label for="L_username" class="layui-form-label">用戶名</label><div class="layui-input-inline"><input type="text" class="layui-input" name="userName" id="L_username" placeholder="Admin..."/></div></div> <div class="layui-form-item"><label for="L_pass" class="layui-form-label">密碼</label><div class="layui-input-inline"><input class="layui-input" type="password" name="userPassword" placeholder="Password..."></div></div><div class="layui-form-item"><label for="L_vercode" class="layui-form-label">驗證碼</label><div class="layui-input-inline"><input type="text" class="layui-input" placeholder="點擊圖片切換" autocomplete="off" required name = "validationCode" ></div><div class="layui-form-mid"><span><img src="ValidationCodeServlet" id="CreateCheckCode" onclick="change()"/></span></div></div><div class="layui-form-item"><input class="layui-btn" type="submit" name="login" value="登錄"/></div></form></div></div></div></div></div>
</div>
<script type="text/javascript">
function change(){ document.getElementById("CreateCheckCode").src="ValidationCodeServlet?"+Math.random(); }
</script>
配置web.xml文件
<servlet><description>com.FM.servlet</description><display-name>com.FM.servlet.ValidationCodeServlet</display-name><servlet-name>ValidationCodeServlet</servlet-name><servlet-class>com.FM.servlet.ValidationCodeServlet</servlet-class></servlet>
<servlet-mapping><servlet-name>ValidationCodeServlet</servlet-name><url-pattern>/ValidationCodeServlet</url-pattern></servlet-mapping>
后臺
package com.FM.servlet;import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.OutputStream;
import java.util.Random;public class ValidationCodeServlet extends HttpServlet {private static final long serialVersionUID = 1L;public ValidationCodeServlet() {super();}protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//獲得驗證碼集合的長度int charsLength = codeChars.length();//下面3條記錄是關閉客戶端瀏覽器的緩沖區//這3條語句都可以關閉瀏覽器的緩沖區,但是由于瀏覽器的版本不同,對這3條語句的支持也不同//因此,為了保險起見,同時使用這3條語句來關閉瀏覽器的緩沖區resp.setHeader("ragma", "No-cache");resp.setHeader("Cache-Control", "no-cache");resp.setDateHeader("Expires", 0);//設置圖形驗證碼的長和寬int width = 90, height = 30;BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);Graphics g = image.getGraphics(); //獲得用于輸出文字的Graphics對象Random random = new Random();g.setColor(getRandomColor(180, 250));g.fillRect(0, 0, width, height);g.setFont(new Font("Times New Roman",Font.ITALIC,height));g.setColor(getRandomColor(120, 180));//用戶保存最后隨機生成的驗證碼StringBuilder validationCode = new StringBuilder();//驗證碼的隨機字體String[] fontNames = {"Times New Roman","Book antiqua","Arial"};//隨機生成4個驗證碼for(int i = 0; i < 4; i++){//隨機設置當前驗證碼的字符的字體g.setFont(new Font(fontNames[random.nextInt(3)],Font.ITALIC,height));//隨機獲得當前驗證碼的字符char codeChar = codeChars.charAt(random.nextInt(charsLength));validationCode.append(codeChar);//隨機設置當前驗證碼字符的顏色g.setColor(getRandomColor(10, 100));//在圖形上輸出驗證碼字符,x和y都是隨機生成的g.drawString(String.valueOf(codeChar), 16*i + random.nextInt(7), height-random.nextInt(6));}//獲得HttpSession對象HttpSession session = req.getSession();//設置session對象5分鐘失效session.setMaxInactiveInterval(5*60);//將驗證碼保存在session對象中,key為validation_codesession.setAttribute("validation_code", validationCode.toString());//關閉Graphics對象g.dispose();OutputStream outS = resp.getOutputStream();ImageIO.write(image, "JPEG", outS);}protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response);}//圖形驗證碼的字符集,系統將隨機從這個字符串中選擇一些字符作為驗證碼private static String codeChars = "123456789abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ";//返回一個隨機顏色private static Color getRandomColor(int minColor, int maxColor){Random random = new Random();if(minColor > 255){minColor = 255;}if(maxColor > 255){maxColor = 255;}//獲得r的隨機顏色值int red = minColor + random.nextInt(maxColor-minColor);//gint green = minColor + random.nextInt(maxColor-minColor);//bint blue = minColor + random.nextInt(maxColor-minColor);return new Color(red,green,blue);}
}
效果圖:
Springboot添加驗證碼
項目結構
依賴
<!-- 驗證碼 --><dependency><groupId>com.github.penggle</groupId><artifactId>kaptcha</artifactId><version>2.3.2</version></dependency>
控制類
CommonController
package com.habse.car_position.Controller;import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;/*
驗證碼*/@Controller
public class CommonController {@Autowiredprivate DefaultKaptcha captchaProducer;@GetMapping("/common/kaptcha")public void defaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {byte[] captchaOutputStream = null;ByteArrayOutputStream imgOutputStream = new ByteArrayOutputStream();try {//生產驗證碼字符串并保存到session中String verifyCode = captchaProducer.createText();httpServletRequest.getSession().setAttribute("verifyCode", verifyCode);BufferedImage challenge = captchaProducer.createImage(verifyCode);ImageIO.write(challenge, "jpg", imgOutputStream);} catch (IllegalArgumentException e) {httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);return;}captchaOutputStream = imgOutputStream.toByteArray();httpServletResponse.setHeader("Cache-Control", "no-store");httpServletResponse.setHeader("Pragma", "no-cache");httpServletResponse.setDateHeader("Expires", 0);httpServletResponse.setContentType("image/jpeg");ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream();responseOutputStream.write(captchaOutputStream);responseOutputStream.flush();responseOutputStream.close();}
}
KaptchaConfig
package com.habse.car_position.config;import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;import java.util.Properties;@Component
public class KaptchaConfig {@Beanpublic DefaultKaptcha getDefaultKaptcha(){DefaultKaptcha defaultKaptcha = new DefaultKaptcha();Properties properties = new Properties();properties.put("kaptcha.border", "no");properties.put("kaptcha.textproducer.font.color", "blue");properties.put("kaptcha.image.width", "140");properties.put("kaptcha.image.height", "40");properties.put("kaptcha.textproducer.font.size", "30");properties.put("kaptcha.session.key", "verifyCode");properties.put("kaptcha.textproducer.char.space", "5");Config config = new Config(properties);defaultKaptcha.setConfig(config);return defaultKaptcha;}
}
前端頁面
<label class="block input-icon"><input type="text" name="verifyCode" placeholder="請輸入驗證碼" style="width: 130px"><img alt="單擊圖片刷新!" class="pointer" src="/common/kaptcha"onclick="this.src='/common/kaptcha?d='+new Date()*1" style="margin-left: 10px;"></label>