您的位置:首页 > 编程语言 > Java开发

javaweb中使用servlet实现验证码

2017-11-21 21:35 525 查看

1、jsp页面

在jsp页面中,我们要有下面几部分:
1.输入框
2.验证码图片
3.看不清按钮
4.提交按钮


预期效果:



思路:



2、jsp页面代码:

<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
--><
4000
/span>
<script type="text/javascript">
//reloadCode方法:实现"点击看不清刷新"的功能
function reloadCode(){
//time变量的功能是强制刷新,忽略浏览器的缓存机制
var time = new Date().getTime();
document.getElementById("imagecode").src="<%=request.getContextPath() %>/servlet/servletImage?d="+time;//传进的time变量,因为time在变化,所以url也在变化,因此可以说是强制刷新
}
</script>

</head>

<body>
<!--表单的方式跳转到loginservlet-->
<form action="<%=request.getContextPath() %>/servlet/loginservlet" method = "get">
验证码:<input type="text" name="checkcode"/>
<img alt="验证码" id="imagecode" src="<%=request.getContextPath() %>/servlet/servletImage"><!--src的方式实现链接到servletImage-->
<a href="javascript: reloadCode();">看不清楚,换一张!</a>
<input type="submit" value="提交" />
</form>
</body>
</html>


3、servletImage

该servlet实现的主要功能是描绘出验证码的图片,里面随机画出4个字母与数字的组合,因为在jsp页面中只用到了get方法跳转,所以重写servlet中的doget方法。




package servlet;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.PrintWriter;
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 servletImage extends HttpServlet {

/**
* Constructor of the object.
*/
public servletImage() {
super();
}

/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}

/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//验证码是通过img标签触发的,所以是get方式,重写servlet方法:
/*
* BufferedImage(int width, int height, int imageType)
构建了一个 BufferedImage一个预定义的图像类型。
TYPE_INT_RGB  代表8位RGB分量包装成整数像素的图像。
*/
BufferedImage bi = new BufferedImage(68,22,BufferedImage.TYPE_INT_RGB);
Graphics g = bi.getGraphics();
Color c = new Color(200,150,255);
g.setColor(c);//背景颜色
g.fillRect(0, 0, 68, 22);//背景框

//字母数字组合:
char[] ch = "ABCDEFGHIJKLMNOPQRSTUVEXYZ123456789".toCharArray();
Random r = new Random();
int len = ch.length;
int index;
StringBuffer sb = new StringBuffer();
for(int i =0;i<4;i++){
index = r.nextInt(len);//随机获得一个起始位置
g.setColor(new Color(r.nextInt(88),r.nextInt(188),r.nextInt(255)));//给字体一个随机的颜色
g.drawString(ch[index]+"", (i*15)+3, 18);
sb.append(ch[index]);
}
request.getSession().setAttribute("piccode", sb.toString());//将生产的验证码保存下来,以便之后的检验输入是否一致
ImageIO.write(bi,"JPG",response.getOutputStream());
}

/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println("  <BODY>");
out.print("    This is ");
out.print(this.getClass());
out.println(", using the POST method");
out.println("  </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}

/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}

}


4、loginServlet

该servlet主要实现验证输入的验证码和之前的图片上的验证码是否一致,之前的图片上的验证码保存在了session中


package servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class loginservlet extends HttpServlet {

/**
* Constructor of the object.
*/
public loginservlet() {
super();
}

/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}

/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//首先获得之前保存在session中的验证码
String piccode = (String) request.getSession().getAttribute("piccode");
String checkcode = request.getParameter("checkcode");
response.setContentType("text/html;charset =UTF-8");
PrintWriter out = response.getWriter();
//response.setContentType("text/html;charset =UTF-8");
if(checkcode.equals(piccode)){
out.print("输入正确");
}else{
out.print("输入不正确!");
}
out.flush();
out.close();
}

/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println("  <BODY>");
out.print("    This is ");
out.print(this.getClass());
out.println(", using the POST method");
out.println("  </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}

/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  servlet java web 验证码