Struts2實(shí)現(xiàn)生成動態(tài)驗證碼并驗證實(shí)例代碼
一、基本流程:
產(chǎn)生一個驗證碼頁面(很?。度氲奖韱沃小c(diǎn)擊可以刷新頁面→表單提交時驗證。
二、方法:
1、定義TestAction,實(shí)現(xiàn)畫圖方法
package com.zhuguang.action;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;
import com.opensymphony.xwork2.ActionSupport;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
public class TestAction extends ActionSupport implements SessionAware,ServletResponseAware
{
private Map<String, Object> session;
private HttpServletResponse response;
private static final long serialVersionUID = 1L;
private String chknumber;
@Override
public String execute() throws Exception
{
response.setHeader("Cache-Control", "no-cache");
int width=50; //圖片寬度
int height=20; //圖片高度
BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
Graphics graphics=image.createGraphics();
graphics.setColor(this.getColor()); //背景顏色
graphics.fillRect(0, 0, width, height);
graphics.setFont(new Font("Arial",Font.BOLD,18));
graphics.setColor(this.getColor()); //字的顏色
String number=String.valueOf(System.currentTimeMillis()%9000+1000); //生成四位隨機(jī)數(shù)
session.put("randomCode", number); //寫入session中
graphics.drawString(number, (int)(width*0.1), (int)(height*0.8));
graphics.dispose();
JPEGImageEncoder encoder=JPEGCodec.createJPEGEncoder(response.getOutputStream());
encoder.encode(image);
response.getOutputStream().flush(); //刷新到頁面生成圖片
response.getOutputStream().close(); //關(guān)閉writer
return null;
}
private Color getColor(){
int red=(int)(Math.random()*1000%256);
int green=(int)(Math.random()*1000%256);
int blue=(int)(Math.random()*1000%256);
return new Color(red,green,blue);
}
public String getChknumber()
{
return chknumber;
}
public void setChknumber(String chknumber)
{
this.chknumber = chknumber;
}
@Override
public void setSession(Map<String, Object> session)
{
// TODO Auto-generated method stub
this.session = session;
}
@Override
public void setServletResponse(HttpServletResponse response)
{
// TODO Auto-generated method stub
this.response = response;
}
}
注意用到session和response
2、在struts.xml文件中注冊:
<action name="randomCode" class="com.zhuguang.action.TestAction"> </action>
其中不返回任何信息,這樣就不會跳轉(zhuǎn)頁面
3、jsp頁面編寫
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib uri="/struts-tags" prefix="s" %>
<%
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>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
<!--
function reloadcode(obj,base){
var rand=new Date().getTime(); //這里用當(dāng)前時間作為參數(shù)加到url中,是為了使URL發(fā)生變化,這樣驗證碼才會動態(tài)加載,
//只是一個干擾作用,無確實(shí)意義,但卻又非常巧妙,呵呵
obj.src=base+"randomCode.action?abc="+rand; //其實(shí)服務(wù)器端是沒有abc的字段的。
}
//-->
</script>
<title>測試頁面</title>
</head>
<body>
<form action="testLogin" method="post">
Username<input type="text" name="name"><br>
Password<input type="text" name="password"><br>
驗證碼:<input type="text" name="chknumber" id="chknumber" maxlength="4" class="chknumber_input">
<img title="看不清楚請點(diǎn)擊這里" width="50" height="20" src="<%=basePath%>randomCode.action" id="safecode" onclick="reloadcode(this,'<%=basePath%>')" /><br>
<input type="submit" value="Loginin">
</form>
</body>
</html>
4、驗證
(1)在Action中添加一個驗證方法
public String testLogin()
{
if(session.get("randomCode").equals(chknumber))
{
return SUCCESS;
}
else
{
return ERROR;
}
}
(2)在struts.xml中進(jìn)行注冊
<action name="testLogin" class="com.zhuguang.action.TestAction" method="testLogin"> <result name="success">success.jsp</result> <result name="error">error.jsp</result> </action>
以上所述是小編給大家介紹的Struts2實(shí)現(xiàn)生成動態(tài)驗證碼并驗證實(shí)例代碼,希望對大家有所幫助!
相關(guān)文章
Java Swing實(shí)現(xiàn)簡單的體重指數(shù)(BMI)計算器功能示例
這篇文章主要介紹了Java Swing實(shí)現(xiàn)簡單的體重指數(shù)(BMI)計算器功能,涉及Java Swing窗口組件布局、響應(yīng)及數(shù)值運(yùn)算相關(guān)操作技巧,需要的朋友可以參考下2017-12-12
SpringBoot種如何使用?EasyExcel?實(shí)現(xiàn)自定義表頭導(dǎo)出并實(shí)現(xiàn)數(shù)據(jù)格式化轉(zhuǎn)換
本文詳細(xì)介紹了如何使用EasyExcel工具類實(shí)現(xiàn)自定義表頭導(dǎo)出,并實(shí)現(xiàn)數(shù)據(jù)格式化轉(zhuǎn)換與添加下拉框操作,通過示例和代碼,展示了如何處理不同數(shù)據(jù)結(jié)構(gòu)和注解,確保數(shù)據(jù)在導(dǎo)出時能夠正確顯示和格式化,此外,還介紹了如何解決特定數(shù)據(jù)類型的轉(zhuǎn)換問題,并提供了解決方案2024-11-11
Java線程池ThreadPoolExecutor的使用及其原理詳細(xì)解讀
這篇文章主要介紹了Java線程池ThreadPoolExecutor的使用及其原理詳細(xì)解讀,線程池是一種多線程處理形式,處理過程中將任務(wù)添加到隊列,然后在創(chuàng)建線程后自動啟動這些任務(wù),線程池線程都是后臺線程,需要的朋友可以參考下2023-12-12
springboot dynamic多數(shù)據(jù)源demo以及常見切換、事務(wù)的問題
這篇文章主要介紹了springboot dynamic多數(shù)據(jù)源demo以及常見切換、事務(wù)的問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-07-07
Elasticsearch 映射參數(shù)詳解 fields
這篇文章主要介紹了fields Elasticsearch 映射參數(shù)fields,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-07-07
如何使用Mockito調(diào)用靜態(tài)方法和void方法
這篇文章主要介紹了如何使用Mockito調(diào)用靜態(tài)方法和void方法的操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-07-07

