验证码刷新与提交示例(Jsp+Servlet+jquery+ajax)
环境
- 1、前端jsp
- 2、服务器tomcat
- 3、服务端servlet
- 4、使用tomcat发布项目的相对路径(你写代码的工程目录和发布到tomcat可以访问的目录是不一样的)
![这里写图片描述](https://img-blog.csdn.net/20170620183403412?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvdTAxMzYzMjg1NA==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
verify.jsp
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" isELIgnored="false"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<base href="<%=basePath%>">
<title>验证码</title>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.0.js"></script>
<script src="jquery.form.js"></script>
</head>
<body>
<div>
<input id="verifytext" style="color: black;" type="text" name="verifytext" maxlength="4" width="50" placeholder="验证码" />
<span>
<img src="jsp/get_verify_pic.jsp" id="verifypic_img">
</span>
<a href="javascript:void(0)" id="verifypic_a">看不清?点击图片更换</a>
</div>
<div >
<button id="btn">保存内容</button>
</div>
</body>
<script type="text/javascript">
$("#btn").click(function(){
var verify = $("#verifytext").val();
$.ajax({
type : 'POST',
url : "VerifySerlvet",
data : {
verifycode : verify,
},
success : function(data, textStatus, jqXHR) {
alert("data:"+data);
},
dataType : "json"
});
});
$("#verifypic_img").click(function () {
var timestamp = new Date().getTime();
$("#verifypic_img").attr('src',$("#verifypic_img").attr('src') + '?' +timestamp );
});
$("#verifypic_a").click(function () {
var timestamp = new Date().getTime();
$("#verifypic_img").attr('src',$("#verifypic_img").attr('src') + '?' +timestamp );
});
</script>
</html>
get_verify_pic.jsp(验证码生成工具)
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ page contentType="image/jpeg"
import="java.awt.*,java.awt.image.*,java.util.*,javax.imageio.*"%>
<%!Color getRandColor(int fc, int bc) {
Random random = new Random();
if (fc > 255)
fc = 255;
if (bc > 255)
bc = 255;
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
}%>
<%
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
int width = 70, height = 32;
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
Random random = new Random();
g.setColor(getRandColor(200, 250));
g.fillRect(0, 0, width, height);
g.setFont(new Font("宋体", Font.PLAIN, 20));
g.setColor(Color.black);
g.drawRect(0, 0, width - 1, height - 1);
g.setColor(getRandColor(160, 200));
for (int i = 0; i < 155; i++) {
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(12);
int yl = random.nextInt(12);
g.drawLine(x, y, x + xl, y + yl);
}
char[] cs = new char[] { '1', '2', '3', '4', '5', '6', '7', '8',
'9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'A',
'B', 'M' };
String sRand = "";
for (int i = 0; i < 4; i++) {
char c = cs[random.nextInt(cs.length)];
String rand = new Character(c).toString();
sRand += rand;
g.setColor(new Color(20 + random.nextInt(110), 20 + random
.nextInt(110), 20 + random.nextInt(110)));
g.drawString(rand, 13 * i + 6, 20);
}
g.dispose();
try {
ImageIO.write(image, "JPEG", response.getOutputStream());
session.setAttribute("rand", sRand);
} catch (Exception e) {
e.getMessage();
} finally {
out.clear();
out = pageContext.pushBody();
}
%>
VerifySerlvet.java
package com.iamzhuwh.pmc;
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;
import com.google.gson.Gson;
/**
* Servlet implementation class FormSerlvet
*/
public class VerifySerlvet extends HttpServlet {
private static final long serialVersionUID = 1L;
public VerifySerlvet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/json;charset=utf-8");
String verifycode = request.getParameter("verifycode");
System.out.println("FormSerlvet verifycode:"+verifycode);
String json = "";
PrintWriter writer = null;
try {
json = new Gson().toJson(new Result(1,"success"));
writer = response.getWriter();
} catch (Exception e) {
json = new Gson().toJson(new Result(0,"error"));
e.printStackTrace();
}finally {
writer.write(json);
if(writer!=null)writer.close();
}
}
}
class Result {
private int status;
private String content;
public Result() {
super();
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Result(int status, String content) {
super();
this.status = status;
this.content = content;
}
@Override
public String toString() {
return "Result [status=" + status + ", content=" + content + "]";
}
}