验证码
2016-04-19 20:35
423 查看
生成四位数的验证码:
jsp页面:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>用户登录</title>
<jsp:include page="/inc.jsp"></jsp:include>
<script type="text/javascript">
</script>
</head>
<body>
<div
style="width: 300px; height: 200px; background: #f0f0f0; border: 0px solid #ff0000; margin-left: 500px; margin-top: 100px; padding: 10px;">
<form id="admin_login_from">
<table border="0" width="300" height="150" cellpadding="0"
cellspacing="0">
<caption>用户登录</caption>
<tr>
<td>用户名</td>
<td><input type="text" id=userName name="userName"
maxlength="50"></td>
</tr>
<tr>
<td>密 码</td>
<td><input type="password" id="userPwd" name="userPwd"
maxlength="30"></td>
</tr>
<tr>
<td>验证码</td>
<td><input type="text" name="yan" id="yan" onblur="yanz()" />
<input type="image" width="50" height="20"
src="<%=request.getContextPath()%>/login/getImg.action" /> <span
id="resYan"></span></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="button" value="提交"
onclick="goLogin();"> <input type="button"
value="注册" onclick="reg();"></td>
</tr>
</table>
</form>
</div>
</body>
<script type="text/javascript">
var temp=false;
function yanz(){
var yan=$("#yan").val();
$.ajax({
type:"post",
url:"<%=request.getContextPath()%>/login/checkYan.action",
data : {
"yan" : yan
},
dataType : "json",
success : function(res) {
temp = res.success;
if (res.success) {
} else {
alert("验证码错误");
}
}
});
}
function goLogin() {
var data = $("#admin_login_from").serialize();
$.ajax({
type : "POST",
url : "${pageContext.request.contextPath}/login/login.action",
data : data,
dataType : "json",
success : function(data) {
if (data.success) {
location.href = "${pageContext.request.contextPath}/jsps/form/main.jsp"
} else {
alert("用户名或密码错误...");
location.href = "${pageContext.request.contextPath}/login.jsp"
}
}
})
}
</script>
</html>
=========================================================================================================
BaseAction.action
package com.jk.action;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import com.alibaba.fastjson.JSON;
import com.opensymphony.xwork2.ActionSupport;
/**
* 实现ServletRequestAware, ServletResponseAware,ServletContextAware
* 获得request response servletContext
* @author Administrator
*
*/
public class BaseAction extends ActionSupport implements ServletRequestAware,ServletResponseAware{
//当前页
protected int cpage = 1;
//每页展示数据条数
protected int pageSize = 10;
//参数id集合
protected String ids;
public HttpServletRequest request;
public HttpServletResponse response;
public int getCpage() {
return cpage;
}
public void setCpage(int cpage) {
this.cpage = cpage;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public String getIds() {
return ids;
}
public void setIds(String ids) {
this.ids = ids;
}
// 通过接口实例化request
public void setServletRequest(HttpServletRequest request) {
this.request=request;
}
/**
* 通过request获得session
* @return
*/
public HttpSession getSession(){
return request.getSession();
}
public void setServletResponse(HttpServletResponse response) {
this.response=response;
}
public String yanzhengma() throws Exception {
// response.setContentType("image/jpeg");
// response.setHeader("Pragma", "No-cache");
// response.setHeader("Cache-Control", "no-cache");
// response.setDateHeader("Expires", 0);
HttpSession session = request.getSession();
// 在内存中创建图象
int width = 70, height = 23;
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("Times New Roman", Font.PLAIN, 24));
// 画边框
g.setColor(getRandColor(160, 200));
g.drawRect(0, 0, width - 1, height - 1);
// 随机产生155条干扰线,使图象中的认证码不易被其它程序探测到
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);
}
// 取随机产生的认证码(4位数字)
String sRand = "";
for (int i = 0; i < 4; i++) {
String rand = String.valueOf(random.nextInt(10));
sRand += rand;
// 将认证码显示到图象中
g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
// 调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成
g.drawString(rand, 13 * i + 14, 20);
}
//
// // 将认证码存入SESSION
session.setAttribute("verifyCode", sRand);
// 图象生效
g.dispose();
// 输出图象到页面
ImageIO.write(image, "JPEG",response.getOutputStream());
return null;
}
private 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);
}
public void writeJson(Object object){
try {
String json = JSON.toJSONStringWithDateFormat(object, "yyyy-MM-dd HH:mm:ss");
ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
ServletActionContext.getResponse().getWriter().write(json);
ServletActionContext.getResponse().getWriter().flush();
ServletActionContext.getResponse().getWriter().close();
} catch (Exception e) {
e.printStackTrace();
}
}
public HttpServletRequest getRequest() {
return request;
}
public void setRequest(HttpServletRequest request) {
this.request = request;
}
public HttpServletResponse getResponse() {
return response;
}
public void setResponse(HttpServletResponse response) {
this.response = response;
}
}
=======================================================================================================
action层
/**
* <pre>getImg(显示验证码)
* 创建人:Zq 960668606@qq.com
* 创建时间:2016年3月18日 下午2:51:07
* 修改人:Zq 960668606@qq.com
* 修改时间:2016年3月18日 下午2:51:07
* 修改备注: </pre>
*/
public void getImg() {
try {
yanzhengma();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* <pre>checkYan(验证验证码是否正确)
* 创建人:Zq 960668606@qq.com
* 创建时间:2016年4月19日 下午7:20:05
* 修改人:Zq 960668606@qq.com
* 修改时间:2016年4月19日 下午7:20:05
* 修改备注: </pre>
*/
public void checkYan() {
HttpSession session = request.getSession();
String yanzheng = (String) session.getAttribute("verifyCode");
if (yan.equals(yanzheng)) {
try {
response.getWriter().write("{\"success\":true}");
} catch (IOException e) {
e.printStackTrace();
}
} else {
try {
response.getWriter().write("{\"success\":false}");
} catch (IOException e) {
e.printStackTrace();
}
}
}
jsp页面:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>用户登录</title>
<jsp:include page="/inc.jsp"></jsp:include>
<script type="text/javascript">
</script>
</head>
<body>
<div
style="width: 300px; height: 200px; background: #f0f0f0; border: 0px solid #ff0000; margin-left: 500px; margin-top: 100px; padding: 10px;">
<form id="admin_login_from">
<table border="0" width="300" height="150" cellpadding="0"
cellspacing="0">
<caption>用户登录</caption>
<tr>
<td>用户名</td>
<td><input type="text" id=userName name="userName"
maxlength="50"></td>
</tr>
<tr>
<td>密 码</td>
<td><input type="password" id="userPwd" name="userPwd"
maxlength="30"></td>
</tr>
<tr>
<td>验证码</td>
<td><input type="text" name="yan" id="yan" onblur="yanz()" />
<input type="image" width="50" height="20"
src="<%=request.getContextPath()%>/login/getImg.action" /> <span
id="resYan"></span></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="button" value="提交"
onclick="goLogin();"> <input type="button"
value="注册" onclick="reg();"></td>
</tr>
</table>
</form>
</div>
</body>
<script type="text/javascript">
var temp=false;
function yanz(){
var yan=$("#yan").val();
$.ajax({
type:"post",
url:"<%=request.getContextPath()%>/login/checkYan.action",
data : {
"yan" : yan
},
dataType : "json",
success : function(res) {
temp = res.success;
if (res.success) {
} else {
alert("验证码错误");
}
}
});
}
function goLogin() {
var data = $("#admin_login_from").serialize();
$.ajax({
type : "POST",
url : "${pageContext.request.contextPath}/login/login.action",
data : data,
dataType : "json",
success : function(data) {
if (data.success) {
location.href = "${pageContext.request.contextPath}/jsps/form/main.jsp"
} else {
alert("用户名或密码错误...");
location.href = "${pageContext.request.contextPath}/login.jsp"
}
}
})
}
</script>
</html>
=========================================================================================================
BaseAction.action
package com.jk.action;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import com.alibaba.fastjson.JSON;
import com.opensymphony.xwork2.ActionSupport;
/**
* 实现ServletRequestAware, ServletResponseAware,ServletContextAware
* 获得request response servletContext
* @author Administrator
*
*/
public class BaseAction extends ActionSupport implements ServletRequestAware,ServletResponseAware{
//当前页
protected int cpage = 1;
//每页展示数据条数
protected int pageSize = 10;
//参数id集合
protected String ids;
public HttpServletRequest request;
public HttpServletResponse response;
public int getCpage() {
return cpage;
}
public void setCpage(int cpage) {
this.cpage = cpage;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public String getIds() {
return ids;
}
public void setIds(String ids) {
this.ids = ids;
}
// 通过接口实例化request
public void setServletRequest(HttpServletRequest request) {
this.request=request;
}
/**
* 通过request获得session
* @return
*/
public HttpSession getSession(){
return request.getSession();
}
public void setServletResponse(HttpServletResponse response) {
this.response=response;
}
public String yanzhengma() throws Exception {
// response.setContentType("image/jpeg");
// response.setHeader("Pragma", "No-cache");
// response.setHeader("Cache-Control", "no-cache");
// response.setDateHeader("Expires", 0);
HttpSession session = request.getSession();
// 在内存中创建图象
int width = 70, height = 23;
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("Times New Roman", Font.PLAIN, 24));
// 画边框
g.setColor(getRandColor(160, 200));
g.drawRect(0, 0, width - 1, height - 1);
// 随机产生155条干扰线,使图象中的认证码不易被其它程序探测到
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);
}
// 取随机产生的认证码(4位数字)
String sRand = "";
for (int i = 0; i < 4; i++) {
String rand = String.valueOf(random.nextInt(10));
sRand += rand;
// 将认证码显示到图象中
g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
// 调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成
g.drawString(rand, 13 * i + 14, 20);
}
//
// // 将认证码存入SESSION
session.setAttribute("verifyCode", sRand);
// 图象生效
g.dispose();
// 输出图象到页面
ImageIO.write(image, "JPEG",response.getOutputStream());
return null;
}
private 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);
}
public void writeJson(Object object){
try {
String json = JSON.toJSONStringWithDateFormat(object, "yyyy-MM-dd HH:mm:ss");
ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
ServletActionContext.getResponse().getWriter().write(json);
ServletActionContext.getResponse().getWriter().flush();
ServletActionContext.getResponse().getWriter().close();
} catch (Exception e) {
e.printStackTrace();
}
}
public HttpServletRequest getRequest() {
return request;
}
public void setRequest(HttpServletRequest request) {
this.request = request;
}
public HttpServletResponse getResponse() {
return response;
}
public void setResponse(HttpServletResponse response) {
this.response = response;
}
}
=======================================================================================================
action层
/**
* <pre>getImg(显示验证码)
* 创建人:Zq 960668606@qq.com
* 创建时间:2016年3月18日 下午2:51:07
* 修改人:Zq 960668606@qq.com
* 修改时间:2016年3月18日 下午2:51:07
* 修改备注: </pre>
*/
public void getImg() {
try {
yanzhengma();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* <pre>checkYan(验证验证码是否正确)
* 创建人:Zq 960668606@qq.com
* 创建时间:2016年4月19日 下午7:20:05
* 修改人:Zq 960668606@qq.com
* 修改时间:2016年4月19日 下午7:20:05
* 修改备注: </pre>
*/
public void checkYan() {
HttpSession session = request.getSession();
String yanzheng = (String) session.getAttribute("verifyCode");
if (yan.equals(yanzheng)) {
try {
response.getWriter().write("{\"success\":true}");
} catch (IOException e) {
e.printStackTrace();
}
} else {
try {
response.getWriter().write("{\"success\":false}");
} catch (IOException e) {
e.printStackTrace();
}
}
}
相关文章推荐
- SpriteKit中反转Action需要注意的问题
- SpriteKit中反转Action需要注意的问题
- Android SDK在线更新镜像服务器
- 第八周项目3—指向学生类的指针(1)
- SpriteKit中反转Action需要注意的问题
- zTree实现地市县三级级联Service接口
- hdu 5108 Alexandra and Prime Numbers
- leetcode----最长有效括号字串
- 【数据结构】二叉树的实现(如:默认成员函数、(叶子)节点数、深度、四种遍历)
- 写一个类的构造函数、复制构造函数、析构函数、赋值函数
- swift URL生成
- 正则表达式基础知识整理
- Android Builder模式
- nyoj1058 部分和问题
- 剪切坐标轴
- linux sysstat 安装使用
- 深入研究String StringBuffer StringBuilder 的拼接字符串
- Chilkat----开源站点之VS2010 CKMailMan一个很好的邮件发送开源开发包
- 《校园封神榜》个人工作总结——第二天
- 1000!的结果中如果用十进制表示,有多少位