我们在做登录的时候往往会加上验证码,然后提交form表单到action验证,然而,传统的这种做法往往验证不通过,返回INPUT页面时,出现验证码图片不显示,并抛出空指针异常,遇到这种情况,通常的解决方法是将action页面跳转到input页面的时候定义成重定向,这样则可以解决图片不显示的问题,并不会抛异常,但验证错误信息和文本框输入信息却不会显示在返回页面,这只是我在实际中遇到的问题,当然,传统做法很可能还会带来诸多各种各样问题,AJAX的使用则彻底解决上述种种问题,下面是一个简易登录页面验证流程:
p_w_picpaths.jsp
上面页面没有验证图片生成代码,验证图片生成代码写在
com.CreatImage中,然后再jsp页面
<
%@ page import
="com.CreatImage"%
>导入;
CreatImage.java:
登录页面:
login.jsp
p_w_picpaths.jsp
<%@ page language="java" contentType="p_w_picpath/jpeg ; charset=UTF-8"
pageEncoding="UTF-8" import="java.awt.*,
java.awt.p_w_picpath.*,javax.p_w_picpathio.*,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 p_w_picpath = c.creatImage();
OutputStream b = response.getOutputStream();
%>
<%ImageIO.write(p_w_picpath, "JPEG", response.getOutputStream());
//必须添加以下两行否则tomcat下jsp出现getOutputStream() has already been called for this response异常
out.clear();
out = pageContext.pushBody();
%>
</body>
</html>
pageEncoding="UTF-8" import="java.awt.*,
java.awt.p_w_picpath.*,javax.p_w_picpathio.*,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 p_w_picpath = c.creatImage();
OutputStream b = response.getOutputStream();
%>
<%ImageIO.write(p_w_picpath, "JPEG", response.getOutputStream());
//必须添加以下两行否则tomcat下jsp出现getOutputStream() has already been called for this response异常
out.clear();
out = pageContext.pushBody();
%>
</body>
</html>
CreatImage.java:
package com;
import java.awt.*;
import java.awt.p_w_picpath.*;
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 p_w_picpath = 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 p_w_picpath = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// 获取图形上下文
Graphics g = p_w_picpath.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));
//画边框
//g.setColor(new Color());
//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 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 p_w_picpath;
}
// 得到随机字符
public String randomStr( int n) {
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;
}
public void creatvalidatep_w_picpath(){
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/p_w_picpaths.jsp?a="+Math.random()+"\"/><a href='' οnclick='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 p_w_picpath;
// }
// public void setImage(Image p_w_picpath) {
// this.p_w_picpath = p_w_picpath;
// }
public String getValidate() {
return validate;
}
public void setValidate(String validate) {
this.validate = validate;
}
}
import java.awt.*;
import java.awt.p_w_picpath.*;
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 p_w_picpath = 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 p_w_picpath = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// 获取图形上下文
Graphics g = p_w_picpath.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));
//画边框
//g.setColor(new Color());
//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 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 p_w_picpath;
}
// 得到随机字符
public String randomStr( int n) {
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;
}
public void creatvalidatep_w_picpath(){
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/p_w_picpaths.jsp?a="+Math.random()+"\"/><a href='' οnclick='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 p_w_picpath;
// }
// public void setImage(Image p_w_picpath) {
// this.p_w_picpath = p_w_picpath;
// }
public String getValidate() {
return validate;
}
public void setValidate(String validate) {
this.validate = validate;
}
}
login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
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/creatp_w_picpath.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%>/p_w_picpaths.jsp?a="+Math.random();
}
</script>
</head>
< body >
< form action="<%=path % >/upload/creatp_w_picpath.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 % >/p_w_picpaths.jsp"/> <a href="#" οnclick="changeCode();">看不清,换一张?</a></td>
</tr>
</table>
</div>
< input type ="button" name ="button" value ="submit" onclick ="getXML();" />
</form>
</body>
</html>
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/creatp_w_picpath.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%>/p_w_picpaths.jsp?a="+Math.random();
}
</script>
</head>
< body >
< form action="<%=path % >/upload/creatp_w_picpath.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 % >/p_w_picpaths.jsp"/> <a href="#" οnclick="changeCode();">看不清,换一张?</a></td>
</tr>
</table>
</div>
< input type ="button" name ="button" value ="submit" onclick ="getXML();" />
</form>
</body>
</html>
转载于:https://blog.51cto.com/java123/81690