我們在做登錄的時候往往會加上驗證碼,然後提交form表單到action驗證,然而,傳統的這種做法往往驗證不通過,返回INPUT頁面時,出現驗證碼圖片不顯示,並拋出空指針異常,遇到這種情況,通常的解決方法是將action頁面跳轉到input頁面的時候定義成重定向,這樣則可以解決圖片不顯示的問題,並不會拋異常,但驗證錯誤信息和文本框輸入信息卻不會顯示在返回頁面,這只是我在實際中遇到的問題,當然,傳統做法很可能還會帶來諸多各種各樣問題,AJAX的使用則徹底解決上述種種問題,下面是一個簡易登錄頁面驗證流程:
p_w_picpaths.jsp
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:
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='' 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 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
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="#" onclick="changeCode();">看不清,換一張?</a></td>
</tr>
</table>
</div>
<input type="button" name="button" value="submit" onclick="getXML();"/>
</form>
</body>
</html>