验证码生成
- 效果
- 一,生成验证码
- 二,页面收到验证码
- 三,验证验证码是否填写正确
效果
-
点击验证码可切换
-
给出提示
一,生成验证码
package servlet;import java.io.IOException;import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import cn.dsna.util.images.ValidateCode;public class ShowVerifyCode extends HttpServlet {/*** */private static final long serialVersionUID = 1L;@Overrideprotected void service(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {req.setCharacterEncoding("UTF-8");resp.setContentType("text/html;charset=utf-8");// 长100 宽100 4个字母 5 条干扰线的验证码ValidateCode validateCode = new ValidateCode(100, 50, 4, 4);ServletOutputStream out = resp.getOutputStream();String code = validateCode.getCode();// 验证码字符串保存到session对象req.getSession().setAttribute("code", code);// 把验证码图片写出去validateCode.write(out);out.close();}}
二,页面收到验证码
<script type="text/javascript">// 刷新验证码!function refresh_code(obj) {// 多次请求obj.src = "showVerifyCode?id=" + new Date().getMilliseconds();}function check_verify_code(obj) {var ajax = new XMLHttpRequest();ajax.open("post", "checkVerifyCodeServlet?verifyCode=" + obj.value, true);ajax.onreadystatechange = function() {if (ajax.readyState == 4 && ajax.status == 200) {// response succeed...if (ajax.responseText == "false") {alert("验证码错误!");// disable submit commit...} else {// submit... do some code...}}};ajax.send(null);}</script>
- 图片src访问servlet,接收验证码图片
<form action="">name: <input type="text" name="name" /> <br/>verifyCode:<input type="text" name="verifyCode" onblur="check_verify_code(this)"/> <img src="showVerifyCode" onclick="refresh_code(this)"></form>
三,验证验证码是否填写正确
protected void service(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {Object code = req.getSession().getAttribute("code");String page_code = req.getParameter("verifyCode");System.out.println("生成的验证码 " + code + "\t页面验证码 " + page_code);PrintWriter out = resp.getWriter();if (code.toString().equalsIgnoreCase(page_code)) {// 页面验证码 = 后台的验证码!out.write("true");} else {out.write("false");}out.close();}