- 浏览: 62793 次
- 性别:
- 来自: 广州
文章分类
最新评论
AJAX验证jsp页面验证码
在做登录的时候往往会加上验证码,然后提交form表单到action验证,然而,传统的这种做法往往验证不通过,返回INPUT页面时,出现验证码图片不显示,并抛出空指针异常,遇到这种情况,通常的解决方法是将action页面跳转到input页面的时候定义成重定向,这样则可以解决图片不显示的问题,并不会抛异常,但验证错误信息和文本框输入信息却不会显示在返回页面,这只是我在实际中遇到的问题,当然,传统做法很可能还会带来诸多各种各样问题,AJAX的使用则彻底解决上述种种问题,下面是一个简易登录页面验证流程:images.jsp
<%@ page language="java" contentType="image/jpeg ; charset=UTF-8"
pageEncoding="UTF-8" import="java.awt.*,
java.awt.image.*,javax.imageio.*,java.io.*"%>
<%@ page import ="com.CreatImage"%>
<%@ taglib uri="/webwork" prefix="ww" %>
<!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>Insert title here</title>
</head>
<body>
<%
response.setHeader("Pragma","No-cache");
response.setHeader("Cache-Control","no-cache");
response.setDateHeader("Expires", 0);
CreatImage c = new CreatImage();
BufferedImage image = c.creatImage();
OutputStream b = response.getOutputStream();
%>
<%ImageIO.write(image, "JPEG", response.getOutputStream());
//必须添加以下两行否则tomcat下jsp出现getOutputStream() has already been called for this response异常
out.clear();
out = pageContext.pushBody();
%>
</body>
</html>
上面页面没有验证图片生成代码,验证图片生成代码写在com.CreatImage中,然后再jsp页面<%@ page import ="com.CreatImage"%>导入;
CreatImage.java:
package com;
import java.awt.*;
import java.awt.image.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.opensymphony.webwork.ServletActionContext;
import com.opensymphony.xwork.ActionSupport;
public class CreatImage extends ActionSupport{
/**
*
*/
private static final long serialVersionUID = 1L;
public String sRand="";
Image image = null;
public 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 BufferedImage creatImage(){
// 在内存中创建图象
int width=60, height=20;
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,18));
// 随机产生155条干扰线,使图象中的认证码不易被其它程序探测到 public String randomStr(int n) { public void creatvalidateimage(){ 登录页面: <%@ page language="java" contentType="text/html; charset=UTF-8"
//画边框
//g.setColor(new Color());
//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);
}
// 取随机产生的认证码(4位数字)
//String rand = request.getParameter("rand");
//rand = rand.substring(0,rand.indexOf("."));
String str1=randomStr(4);// 得到随机字符
HttpSession session = ServletActionContext.getRequest().getSession();
session.setAttribute("validatenumber",str1);
for (int i=0;i<4;i++){
String rand=str1.substring(i,i+1);
// 将认证码显示到图象中
g.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110)));
//调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成
g.drawString(rand,13*i+6,16);
}
// 图象生效
g.dispose();
return image;
}
// 得到随机字符
String str1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
String str2 = "";
int len = str1.length() - 1;
double r;
for (int i = 0; i < n; i++) {
r = (Math.random()) * len;
str2 = str2 + str1.charAt((int) r);
}
return str2;
}
HttpSession session = ServletActionContext.getRequest().getSession();
String valnumber = (String)session.getAttribute("validatenumber");
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType("text/html;charset=utf-8");
PrintWriter out;
if(validate.equals(valnumber)){
session.invalidate();//清空session
message="validate success";
try {
out = ServletActionContext.getResponse().getWriter();
out.println(message);
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}else
session.removeAttribute("validatenumber");
message="validate is error";
try {
out = ServletActionContext.getResponse().getWriter();
out.println(message);
out.println("<table>");
out.println("<tr>");
out.println("<td>userName:<input type='text' id='name' value='"+name+"'/></td>");
out.println("</tr>");
out.println("<tr>");
out.println("<td>userPassword:<input type='password' id='password' value='"+password+"'/></td>");
out.println("</tr>");
out.println("<tr>");
out.println("<td>validate:<input type='text' id='validate'/><img src=\"http://localhost:8088/uploadfile/images.jsp?a="+Math.random()+"\"/><a href='' onclick='changeCode()'>看不清,换一张?</a></td>");
out.println("</tr>");
out.println("</table>");
out.flush();
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private String validate;
private String message;
private String name;
private String password;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
// public Image getImage() {
// return image;
// }
// public void setImage(Image image) {
// this.image = image;
// }
public String getValidate() {
return validate;
}
public void setValidate(String validate) {
this.validate = validate;
}
}
login.jsp
pageEncoding="UTF-8"%>
<%@ taglib uri="/webwork" prefix="ww" %>
<%
String path = request.getContextPath();
%>
<!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>Insert title here</title>
<script src="<%=path%>/js/prototype.js"></script>
<script>
function getXML(){
var name = document.getElementById("name").value;
var password = document.getElementById("password").value;
var validate = document.getElementById("validate").value;
var url="<%=path %>/upload/creatimage.action?password="+password+"&validate="+validate;
var myAjax = new Ajax.Request(
url,
{
method:'post',
onComplete:showResponse,
parameters:"name="+name,
asynchronous:true
}
);
}
function showResponse(xmlrequest){
var text = xmlrequest.responseText;
document.getElementById("uploadanotherfile").innerHTML=text;
}
function changeCode()
{
document.getElementById("cc").src="<%=path%>/images.jsp?a="+Math.random();
}
</script>
</head>
<body>
<form action="<%=path %>/upload/creatimage.action" method="post">
<div id="uploadanotherfile">
<table>
<tr>
<td>userName:<input type="text" id="name" value="<ww:property value="name"/>"/></td>
</tr>
<tr>
<td>userPassword:<input type="password" id="password" value="<ww:property value="password"/>"/></td>
</tr>
<tr>
<td>validate:<input type="text" id="validate"><img alt="" id="cc" src="<%=path %>/images.jsp"/><a href="#" onclick="changeCode();">看不清,换一张?</a></td>
</tr>
</table>
</div>
<input type="button" name="button" value="submit" onclick="getXML();"/>
</form>
</body>
</html>
发表评论
-
java泛型
2015-08-30 18:04 407一. 泛型概念的提出(为什么需要泛型)? 首先,我们看下下 ... -
getOutputStream() has already been called for this response 出错的原因
2011-09-03 01:05 1047java.lang.IllegalStateException ... -
判断是否为素数
2011-08-19 22:39 936package ch15; public class Pri ... -
tomcat认识
2011-07-19 11:29 688tomcat的组件结构2007-05-23 ... -
看了这篇文章之后收益挺大的
2011-04-27 19:44 695介绍Java学习的一些主线 ... -
再次熟记
2011-04-19 14:14 471数据类型 1、基本数据类型 数值型 ... -
课后练习01
2011-04-15 16:25 8531、对于许多数据结构来说,可以(插入)一条记录,可以(查找), ... -
word不能直接打开老是出现安全模式是什么原因?
2011-04-06 16:07 1575故障现象:今天在打开一个word文件时出错,重新启动word出 ... -
小练日期处理方法_DAO
2011-03-24 20:41 622package com.jianson.DATE; impo ... -
java中的简单日期处理
2011-03-23 10:36 574public class TestDate { publi ... -
stament接口的三个方法:execute、executeupdate、executeuquery
2011-03-17 20:00 1306execute、executeQuery和executeUpd ... -
可投放广告位的博客
2011-03-14 11:45 7781.站点名称: Google自己的博客站占地址: http:/ ... -
application试题
2011-01-28 13:50 550—————O(∩_∩)O ... -
application实现简单的网页计数器--02
2011-01-28 13:17 837————————app ... -
application实现简单的网页计数器--01
2011-01-28 00:05 1708—— ———————————— index.jsp页面 ... -
JDK、SDK、JRE、JVM—初识02
2011-01-25 12:07 731(出自:http://freesea. ... -
JDK、SDK、JRE、JVM—初识01
2011-01-25 11:52 806JDK、SDK、JRE、JVM概念的理解是什么呢?我们 ... -
环境变量的设置
2010-11-09 18:03 725今天在笔记本上准备使 ...
相关推荐
NULL 博文链接:https://javal.iteye.com/blog/1993903
1.在tomcat6.0下jsp出现getOutputStream() has already been called for this response异常的原因和解决方法 在tomcat6.0下jsp中出现此错误一般都是在jsp中使用了输出流(如输出图片验证码,文件下载等),没有...
纠结了半天的 java.lang.IllegalStateException: getOutputStream() has already。这个问题困扰了半天,在网上查阅了大量资料 出这个错误一般就是下面2个.....
验证码出现getOutputStream() has already been called for this response错误解决
解决了getOutputStream() has already been called for this response. 并将产生验证码的逻辑从JSP页面中分离出来,单独写了一个类 便于重用。
NULL 博文链接:https://nethub2.iteye.com/blog/2023937
servlet的response可以对返回的内容和格式进行一些设置。
Returns a boolean indicating whether the named response header has already been set. contextDestroyed(ServletContextEvent) - Method in interface javax.servlet.ServletContextListener Notification ...
.getOutputStream()); out.write(strPostRequest); out.flush(); out.close(); } /*部分删节,请下载细看!!*/ public static void main(String[] args) { String url = ...
* 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 ...
随机获取验证码 public class CheckNumberServlet extends HttpServlet { ... ServletOutputStream sos = response.getOutputStream();…………………………………………………………………………………………
public void code(HttpServletRequest request, HttpServletResponse response) throws IOException{ String[] tableNames = new String[]{};... IOUtils.write(data, response.getOutputStream()); }
out = new PrintWriter(client.getOutputStream(), true); start(); } public void run() { try { int flag = 0; Thread_Counter++; String line = in.readLine(); while (!line....
heads是excel表头,datalist是数据public void createExcelStream(HttpServletResponse response,String filename,String[] heads,List[]> datalist){ try{ OutputStream os = response.getOutputStream();...
OutputStream oStream = socket.getOutputStream(); DataOutputStream dataOutputStream = new DataOutputStream(oStream); dataOutputStream.writeUTF("Hello"); } catch (UnknownHostException e) { ...
getWriter() 和Response.getOutputStream冲突
如果您正在寻找一份JAVA客户端发送POST请求的示例代码,那么我们的资源库将为您提供一切所需。本资源库提供了一份完整的JAVA客户端发送POST请求的示例代码,可以帮助您快速了解如何使用JAVA客户端发送POST请求,同时...
import java.io.*; import java.util.*; import javax.servlet.*; ... public class MyServlet ... OutputStream out_Stream = response.getOutputStream(); out_Stream.write( data ); out_Stream.close(); } }
OutputStream outs = response.getOutputStream();// 获取文件输出IO流 BufferedOutputStream bouts = new BufferedOutputStream(outs); response.setContentType("application/x-download");// 设置response...