JS实现验证码
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ImgServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// 1:声明图片大小
int width = 60;
int height = 25;
// 2:生成内存中的图片
BufferedImage img = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
// 3:获取画笔
Graphics g = img.getGraphics();
g.setColor(new Color(226, 239, 247));
// 4:画背景
g.fillRect(0, 0, width, height);
// 5:设置字体、大小
g.setFont(new Font("宋体", Font.BOLD, 18));
// 6:生成四个数
String sCode = "";
Random r = new Random();
for (int i = 0; i < 4; i++) {
int a = r.nextInt(10);
// 写出这个数
Color c = new Color(r.nextInt(256), r.nextInt(256),
r.nextInt(256));
g.setColor(c);
g.drawString("" + a, i * 15, 24);
sCode += a;
}
// 放到session中
request.getSession().setAttribute("scode", sCode);
// 7:生效
g.dispose(); // 相当于flush()
// 8:输出图片
response.setContentType("image/jpeg");// 设置输出的类型
OutputStream out = response.getOutputStream();
// 输出
ImageIO.write(img, "JPEG", out);
}
}
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// 5:一次性设置所有获取到的参数都是UTF-8
request.setCharacterEncoding("UTF-8");
// 3:设置输出的编码格式和类型
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
// 1:获取用户提交的参数的值
String code = request.getParameter("code");
// 从session中获取验证码
String sCode = (String) request.getSession().getAttribute("scode");
// 判断验证码是否正确
if (!code.equals(sCode)) {
out.print("你的验证码错误。
");
return;
}
}
}
Jsp页面输出:
<form id="form1"action="<%=request.getContextPath()%>/LoginServlet"
method="post">
</form>。