struts---JSP介面驗證碼產生與驗證

來源:互聯網
上載者:User

標籤:pass   mat   success   exe   ati   isp   img   array   comm   

之前想做一個隨機驗證碼的功能,自己也搜尋了一下別人寫的代碼,然後自己重新用struts2實現了一下,現在將我自己實現代碼貼出來!大家有什麼意見都可以指出來!

首先是產生隨機驗證碼圖片的action:

CreateImageAction:

package com.xiaoluo.action;import java.awt.Color;import java.awt.Font;import java.awt.Graphics;import java.awt.image.BufferedImage;import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.util.Random;import javax.imageio.ImageIO;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionSupport;public class CreateImageAction extends ActionSupport{    private ByteArrayInputStream inputStream;    private static int WIDTH = 60;    private static int HEIGHT = 20;    public ByteArrayInputStream getInputStream()    {        return inputStream;    }    public void setInputStream(ByteArrayInputStream inputStream)    {        this.inputStream = inputStream;    }
private static String createRandom() { String str = "0123456789qwertyuiopasdfghjklzxcvbnm"; char[] rands = new char[4]; Random random = new Random(); for (int i = 0; i < 4; i++) { rands[i] = str.charAt(random.nextInt(36)); } return new String(rands); } private void drawBackground(Graphics g) { // 畫背景 g.setColor(new Color(0xDCDCDC)); g.fillRect(0, 0, WIDTH, HEIGHT); // 隨機產生 120 個幹擾點 for (int i = 0; i < 120; i++) { int x = (int) (Math.random() * WIDTH); int y = (int) (Math.random() * HEIGHT); int red = (int) (Math.random() * 255); int green = (int) (Math.random() * 255); int blue = (int) (Math.random() * 255); g.setColor(new Color(red, green, blue)); g.drawOval(x, y, 1, 0); } } private void drawRands(Graphics g, String rands) { g.setColor(Color.BLACK); g.setFont(new Font(null, Font.ITALIC | Font.BOLD, 18)); // 在不同的高度上輸出驗證碼的每個字元 g.drawString("" + rands.charAt(0), 1, 17); g.drawString("" + rands.charAt(1), 16, 15); g.drawString("" + rands.charAt(2), 31, 18); g.drawString("" + rands.charAt(3), 46, 16); System.out.println(rands); } @Override public String execute() throws Exception { HttpServletResponse response = ServletActionContext.getResponse(); // 設定瀏覽器不要緩衝此圖片 response.setHeader("Pragma", "no-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); String rands = createRandom(); BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB); Graphics g = image.getGraphics(); // 產生映像 drawBackground(g); drawRands(g, rands); // 結束映像 的繪製 過程, 完成映像 g.dispose(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ImageIO.write(image, "jpeg", outputStream); ByteArrayInputStream input = new ByteArrayInputStream(outputStream .toByteArray()); this.setInputStream(input); HttpSession session = ServletActionContext.getRequest().getSession(); session.setAttribute("checkCode", rands); input.close(); outputStream.close(); return SUCCESS; }}

以上是產生隨機驗證碼圖片的action,將產生的隨機數放到session裡,然後頁面提交到驗證隨機數的action:

LoginValidateAction:

package com.xiaoluo.action;import javax.servlet.http.HttpSession;import org.apache.struts2.ServletActionContext;import com.opensymphony.xwork2.ActionSupport;public class LoginValidateAction extends ActionSupport{    private String checkCode;        public String getCheckCode()    {        return checkCode;    }    public void setCheckCode(String checkCode)    {        this.checkCode = checkCode;    }    @Override    public String execute() throws Exception    {        return SUCCESS;    }        @Override    public void validate()    {        HttpSession session = ServletActionContext.getRequest().getSession();                String checkCode2 = (String)session.getAttribute("checkCode");                if(!checkCode.equals(checkCode2))        {            this.addActionError("輸入的驗證碼不正確,請重新輸入!");        }    }}

下面是struts.xml配置部分代碼:

      <action name="createImageAction" class="com.xiaoluo.action.CreateImageAction">                <result name="success" type="stream">                    <param name="contentType">image/jpeg</param>                    <param name="inputName">inputStream</param>                </result>        </action>                        <action name="loginValidateAction" class="com.xiaoluo.action.LoginValidateAction">                <result name="success">/success.jsp</result>                <result name="input">/login.jsp</result>            </action>

最後就是jsp部分的代碼:

login.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%@ taglib prefix="s" uri="/struts-tags"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><html>  <head>    <base href="<%=basePath%>">        <title>My JSP ‘login.jsp‘ starting page</title>        <meta http-equiv="pragma" content="no-cache">    <meta http-equiv="cache-control" content="no-cache">    <meta http-equiv="expires" content="0">        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">    <meta http-equiv="description" content="This is my page">    <!--    <link rel="stylesheet" type="text/css" href="styles.css">    -->      </head>    <body>    <h3><font color="blue">帶有驗證碼的登陸介面</font></h3>        <s:form action="loginValidateAction.action" theme="simple">            使用者名稱:<s:textfield name="username"></s:textfield><br>        密碼    :<s:password name="password"></s:password><br>        驗證碼:<s:textfield name="checkCode"></s:textfield>
     
     <!--若要點擊圖片重新整理,重新得到一個驗證碼,要在後面加上個隨機數,這樣保證每次提交過去的都是不一樣的path,防止因為緩衝而使圖片不重新整理--> <img src="createImageAction.action" onclick="this.src=‘createImageAction.action?‘+ Math.random()" title="點擊圖片重新整理驗證碼"/><br> <s:actionerror cssStyle="color:red"/> <s:submit value="提交"></s:submit> </s:form> </body></html>

struts---JSP介面驗證碼產生與驗證

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.