使用插件生成验证码

第一步:导入插件,放在/ValidateCode/WebContent/WEB-INF/lib/中.

下载地址: http://www.java2s.com/Code/Jar/k/Downloadkaptcha23jar.htm
 

第二步:配置web.xml

<servlet>
      <servlet-name>Kaptcha</servlet-name>
      <servlet-class>com.google.code.kaptcha.servlet.KaptchaServlet</servlet-class>
  </servlet>
  <servlet-mapping>
      <servlet-name>Kaptcha</servlet-name>
      <url-pattern>/kaptcha.jpg</url-pattern>
  </servlet-mapping>

第三步:画页面

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript">
       function reloadCode(){
    	   document.getElementById("imgCode").src="/ValidateCode/kaptcha.jpg"+Math.random();
       }
</script>
</head>
<body>
    <form action="/ValidateCode/kapServlet" method="post">
         <label for="username">用户名:</label>
         <input type="text" id="username" name="username"><br>
         <label for="pwd">密&emsp;码:</label>
         <input type="password" id="pwd" name="password"><br>
         <label for="code">验证码:</label>
         <input type="text" name="usercode">
         <img src="/ValidateCode/kaptcha.jpg" id="imgCode" onclick="reloadCode()"><br>
         <input type="submit" value="提交">
    </form>
</body>
</html>

action是表示向何处发送数据,写完servlet验证之后再填写.

第四步:写Servlet

package yyy.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class KapServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
		
		// 假设注册的用户名和密码已经通过校验,我还需要校验验证码是否正确
		// 获取用户在页面输入的验证码
		String userCode = request.getParameter("usercode"); //要与表单中验证码输入框中name属性的值一样.
		// 获取我们后台生成的验证码的结果
		String validateCodeResult =((String)request.getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY));	
		System.out.println(validateCodeResult);
		// 比对两个验证码是否一致
		if(validateCodeResult.equals(userCode)) {
			response.getWriter().write("恭喜,校验成功!");
		} else {
			response.getWriter().write("很遗憾,校验失败!");
		}
	}

		protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

第五步:继续再配置web.xml

<servlet>
       <servlet-name>KapServlet</servlet-name>
       <servlet-class>yyy.servlet.KapServlet</servlet-class>
  </servlet>
  <servlet-mapping>
       <servlet-name>KapServlet</servlet-name>
       <url-pattern>/kapServlet</url-pattern>
  </servlet-mapping>

运行结果:

发布了75 篇原创文章 · 获赞 164 · 访问量 11万+

猜你喜欢

转载自blog.csdn.net/qq_41679818/article/details/100606008