验证码功能
1在页面上修改样式,可以展示验证码
<p style="position: relative;">
<input class="ipt" style="width:150px;" type="text" name="yzm" id="yzm" placeholder="输入验证码" /> <img id="imgCode" src="${pageContext.request.contextPath}/validateCode/create" style="margin-top: 5px;" height="40px" width="100px" onclick="changeImg()">
</p>
页面上还要给验证码图片加上点击事件:
再要我们的url后面添加一个参数随机值,因为相同的url不断的请求,浏览器不会去后台执行代码的,所以搞一个随机值,不断的更改值,骗过浏览器去后台执行代码。
function changeImg(){
console.log("进来了.....");
$("#imgCode")[0].src="${pageContext.request.contextPath}/validateCode/create?data="+Math.random();
}
2在前端或者后台生成验证码,展示在页面上
借助一个工具类 ValidateCode.jar,需要先导入jar包
package com.qfedu.servlet;
import cn.dsna.util.images.ValidateCode;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/validateCode/*")
public class ValidateCodeServlet extends BaseServlet {
public void create(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 第一个参数 图片的宽度
// 2 图片高度
// 3 图片上包含多少个字母
// 4 生成干扰线的数量
ValidateCode validateCode = new ValidateCode(100,40,4,20);
validateCode.createCode();//生成验证码图片
// 每次生成的验证码都要放入session一个,因为我们将来登录的时候要校验用户的验证码是否正确
String code = validateCode.getCode();
req.getSession().setAttribute("VALIDATECODE",code);
validateCode.write(resp.getOutputStream());//通过流的方式传递给页面
}
}
3.提交表单时验证码一定要是正确的。
需要提前在生成验证码的时候就在session中放入验证码的值,便于以后登录时校验
String code = validateCode.getCode();
req.getSession().setAttribute("VALIDATECODE",code);
4.登录校验
HttpSession session = req.getSession();
String validatecode = (String)session.getAttribute("VALIDATECODE");
String yzm = req.getParameter("yzm");
if(!validatecode.equals(yzm)){
resp.getWriter().write("2");
}else{
String username = req.getParameter("username");
String password = req.getParameter("password");
String isJiZhu = req.getParameter("isJiZhu");
System.out.println(username+","+password+","+isJiZhu);
boolean result = adminService.validateLogin(username,password);
if(result){
Cookie usernameCookie = new Cookie("username", username);
Cookie passwordCookie = new Cookie("password", password);
if(isJiZhu.equals("true")){
// 设置7天过期
usernameCookie.setMaxAge(7*3600*24);
passwordCookie.setMaxAge(7*3600*24);
}else{
usernameCookie.setMaxAge(0);
passwordCookie.setMaxAge(0);
}
resp.addCookie(usernameCookie);
resp.addCookie(passwordCookie);
// 将用户名保存在session中便于页面获取数据
session.setAttribute("USERNAME",username);
resp.getWriter().write("1");
}else{
resp.getWriter().write("0");
}
}
}