這里實現(xiàn)我使用到了struts2模擬一個登錄功能來驗證java實現(xiàn)的驗證碼功能。
Java實現(xiàn)驗證碼的步驟:
1、創(chuàng)建RandomImageGenerator.java類,該類實現(xiàn)驗證碼圖片的生成
2、創(chuàng)建一個servlet類,RandomImageServlet.java,將生成的驗證碼輸出到頁面
3、創(chuàng)建一個Action類,LoginAction.java,控制登錄
4、配置struts.xml一個web.xml文件
5、編寫頁面
具體實現(xiàn)用代碼表達
1、創(chuàng)建RandomImageGenerator.java類
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
import javax.imageio.ImageIO;
/**
* 驗證碼生成類
* @author xiaohu
*
*/
public class RandomImageGenerator {
//創(chuàng)建Random對象
static Random random=new Random();
//隨機生成包含驗證碼字符串
public static String random(int num){
//初始化種子
String[] str={"0","1","2","3","4","5","6","7","8","9",
"a","b","c","d","e","f","g","h","i","j",
"k","l","m","n","p","q","r","s","t"};
int number=str.length;
//接收隨機字符
String text = "";
//隨機產(chǎn)生4個字符的字符串
for(int i=0;i<num;i++){
text+=str[random.nextInt(number)];
}
return text;
}
/**
* 隨機產(chǎn)生定義的顏色
*
* @return
*/
private static Color getRandColor() {
Random random = new Random();
Color color[] = new Color[10];
color[0] = new Color(32, 158, 25);
color[1] = new Color(218, 42, 19);
color[2] = new Color(31, 75, 208);
color[3] = new Color(0, 102, 182);
color[4] = new Color(171, 0, 85);
return color[random.nextInt(5)];
}
/**
* 產(chǎn)生隨機字體
*
* @return
*/
private static Font getFont() {
Random random = new Random();
Font font[] = new Font[5];
font[0] = new Font("Ravie", Font.BOLD, 30);
font[1] = new Font("Antique Olive Compact", Font.BOLD, 30);
font[2] = new Font("Forte", Font.BOLD, 30);
font[3] = new Font("Wide Latin", Font.BOLD, 30);
font[4] = new Font("Gill Sans Ultra Bold", Font.BOLD, 30);
return font[random.nextInt(5)];
}
/**
* 生成圖片
* @throws IOException
*/
public static void render(String randomStr,OutputStream out,int width,int height) throws IOException{
//在內(nèi)存中創(chuàng)建圖像
BufferedImage bi=new BufferedImage(width, height, BufferedImage.TYPE_BYTE_INDEXED);
//獲取圖形上下文
Graphics2D g=(Graphics2D) bi.getGraphics();
//話邊框
g.setColor(Color.white);
g.fillRect(0, 0, width, height);
g.setFont(getFont());
g.setColor(Color.BLACK);
//畫認證碼,每個認證碼在不同的水平位置
String str1[]=new String[randomStr.length()];
for(int i=0;i<str1.length;i++){
str1[i]=randomStr.substring(i,i+1);
int w=0;
int x=(i+1)%3;
//隨機生成驗證碼字符水平偏移量
if(x==random.nextInt(7)){
w=30-random.nextInt(7);
}else{
w=30+random.nextInt(7);
}
//隨機生成顏色
g.setColor(getRandColor());
g.drawString(str1[i], 20*i+10, w);
}
//隨機產(chǎn)生干擾點,并用不同的顏色表示,事圖像的認證碼不易被其他程序探測到
for(int i=0;i<100;i++){
int x=random.nextInt(width);
int y=random.nextInt(height);
Color color=new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255));
//隨機畫各種顏色的線
g.setColor(color);
g.drawOval(x, y, 0, 0);
}
//畫干擾線
for(int i=0;i<15;i++){
int x=random.nextInt(width);
int y=random.nextInt(height);
int x1=random.nextInt(width);
int y1=random.nextInt(height);
Color color=new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255));
//隨機畫各種顏色線
g.setColor(color);
g.drawLine(x, y, x1, y1);
}
//圖像生效
g.dispose();
//輸出頁面
ImageIO.write(bi, "jpg", out);
}
public static void main(String[] args) throws FileNotFoundException, IOException {
//獲取隨機字符串
String randomStr=random(5);
System.out.println(randomStr);
//生成圖片
render(randomStr, new FileOutputStream("D://test.jpg"),130,40);
}
}
2、創(chuàng)建RandomImageServlet.java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.tenghu.code.RandomImageGenerator;
public class RandomImageServlet extends HttpServlet {
//圖片寬度
int width=0;
//圖片高度
int height=0;
//圖片上隨機字符個數(shù)
int randomStrNum=0;
public void destroy() {
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
//獲取HttpSession對象
HttpSession session=request.getSession();
//獲取隨機字符串
String randomStr=RandomImageGenerator.random(randomStrNum);
if(null!=session){
//設置參數(shù)
session.setAttribute("randomStr", randomStr);
//設置響應類型,輸出圖片客戶端不緩存
response.setDateHeader("Expires", 1L);
response.setHeader("Cache-Control", "no-cache, no-store, max-age=0");
response.addHeader("Pragma", "no-cache");
response.setContentType("image/jpeg");
//輸出到頁面
RandomImageGenerator.render(randomStr, response.getOutputStream(), width, height);
}
}
public void init() throws ServletException {
//獲取寬度
width=Integer.parseInt(this.getInitParameter("width"));
//獲取高度
height=Integer.parseInt(this.getInitParameter("height"));
//獲取個數(shù)
randomStrNum=Integer.parseInt(this.getInitParameter("num"));
}
}
3、創(chuàng)建LoginAction.java類
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class LoginAction extends ActionSupport{
//用戶名
private String userName;
//密碼
private String password;
//驗證碼
private String code;
private InputStream inputStream;
public InputStream getResult(){
return inputStream;
}
//成功
public String success() throws Exception{
return SUCCESS;
}
//測試登錄
public String testLogin() throws Exception{
//獲取圖片的驗證碼
String randomStr=(String) ActionContext.getContext().getSession().get("randomStr");
if(code.trim().equalsIgnoreCase(randomStr)){
if("admin".equals(userName.trim())&&"admin".equals(password.trim())){
//成功
inputStream=new ByteArrayInputStream("1".getBytes("UTF-8"));
}else{
//用戶名或密碼錯誤
inputStream=new ByteArrayInputStream("2".getBytes("UTF-8"));
}
}else{
//驗證碼錯誤
inputStream=new ByteArrayInputStream("0".getBytes("UTF-8"));
}
return "result";
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}
4、配置struts.xml、web.xml文件
<servlet-mapping>
<servlet-name>RandomImageServlet</servlet-name>
<url-pattern>/verification.do</url-pattern>
</servlet-mapping>
<!-- 配置struts核心過濾器 -->
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
5、編寫測試頁面
成功頁面就部貼出來了,就是一段文字而已
顯示結(jié)果:
新聞熱點
疑難解答