驗證碼外掛EasyCaptcha
阿新 • • 發佈:2022-12-03
1.新增maven依賴
<dependency> <groupId>com.github.whvcse</groupId> <artifactId>easy-captcha</artifactId> <version>1.6.2</version> </dependency>
2.使用工具類
在servlet中建立一個方法只需要兩步就可以在頁面中使用驗證碼
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throwsServletException, IOException { GifCaptcha c = new GifCaptcha(); CaptchaUtil.out(c,req,resp); //req.getSession().setAttribute("captcha","sfsx"); }
CaptchaUtil是EasyCaptcha中引入的工具類,它內部有很多屬性和out方法,其中一個是
public static void out(Captcha captcha, HttpServletRequest request, HttpServletResponse response) throwsIOException { setHeader(response); request.getSession().setAttribute("captcha", captcha.text().toLowerCase()); captcha.out(response.getOutputStream()); }
這個方法會把驗證碼的內容存到session中的captcha上,我們只需要呼叫就可以得到驗證碼的值
3.在頁面中使用驗證碼
<form action="check" method="post"> <label>賬號:<input type="text" name="account"></label><br> <label>密碼:<input type="password" name="pwd"></label><br> <label>驗證碼:<input type="text" name="code"></label> <label><img src="check" onclick="this.src='check?'+ new Date()" alt=""></label> <br> <input type="submit" value="登入"> </form>
check是定義的servlet的名稱,返回後就是驗證碼,新增onclick事件單擊改變驗證碼的內容,new Date()是傳入的時間戳,讓驗證碼的內容隨之改變。頁面效果如下。
最後在登入的時候對驗證碼進行校驗就可以了