JavaWeb 登录实现图片验证码

主要思路:

    1) 打开页面生成随机验证码图片, 可更换图片,通过java后端实现。同时把生成的验证码保存在session作用域中。

    2)用户输入验证码,提交

    3)获取页面提交的验证码 和 保存在session作用域中的验证码,两者比较,相等后删除保存在session作用域中的验证码。

 

1、页面


	

登录页面

用户名:
密 码:
验证码: 验证码 换一张

${errorMsg }

2、servlet

public class LoginServlet extends HttpServlet{
	private static final long serialVersionUID = 1L;
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//生成验证码
		verificationCode(request, response);
		doPost(request, response);
	}
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=UTF-8");
		
		//获得登录的账号和密码
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String requestVerificationCode = request.getParameter("verificationCode");
		System.out.println(requestVerificationCode);
		HttpSession session = request.getSession();
		String sessionVerificationCode = (String) session.getAttribute("verificationCode");
		//验证验证码(忽略验证码大小写)
		if(sessionVerificationCode.equalsIgnoreCase(requestVerificationCode)) {
			session.removeAttribute("verificationCode"); 
                        if(username.equals("admin") && password.equals("admin123")){//登录成功
				//重定向到index.jsp
				response.sendRedirect(request.getContextPath() +"/index.jsp"); 
			}else{//登录失败
				request.setAttribute("errorMsg", "用户名或密码不正确");
				request.getRequestDispatcher("/login.jsp").forward(request, response);
			}
		}else {
			request.setAttribute("errorMsg", "验证码不正确!");
			request.getRequestDispatcher("/login.jsp").forward(request, response);
		}
		
	}
	
	public void verificationCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
		//设置响应的类型格式为图片格式, 并禁止缓存
		response.setContentType("image/jpg");
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		
		VerificationCodeImgUtil vCode = new VerificationCodeImgUtil(120,25,5,50);
		//把随机产生的验证码保存在session作用域中
		request.getSession().setAttribute("verificationCode", vCode.getValidateCode());
		vCode.write(response.getOutputStream(), "jpg");
	}
	
}

3、VerificationCodeImgUtil 类

     Java图片验证码生成工具类

4、测试

  JavaWeb 登录实现图片验证码_第1张图片    JavaWeb 登录实现图片验证码_第2张图片

 

你可能感兴趣的:(JavaWeb)