struts2的驗證碼及利用jquery發送ajax請求並利用json做資料交換

來源:互聯網
上載者:User

image.jsp :

<%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title><script type="text/javascript" src="js/jquery-1.4.min.js"></script><script type="text/javascript">$(function(){    $("#valiCode").blur(function(){        $.post(            "valid",//請求url            {"valiCode":$(this).val()},//請求參數            function(data){//回呼函數                if(data.ok){                    $("#msg").html("<font style='color:red'>驗證碼填寫正確</font>");                }else{                    $("#msg").html("<font style='color:red'>驗證碼填寫錯誤</font>");                    $("#image").attr("src","image?date="+new Date().getTime());                }            },            "json"//返回資料data的格式為json        );    });});</script></head><body><img id="image" src="image"><br><input type="text" name="valiCode" id="valiCode"><span id="msg"></span></body></html>

struts.xml :

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC    "-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"    "http://struts.apache.org/dtds/struts-2.1.7.dtd"><struts>    <package name="demo" extends="json-default">            <action name="image" class="action.ImageAction">            <result name="success" type="stream">                <param name="inputName">image</param>            </result>        </action>                <action name="valid" class="action.ValidImageAction">            <result name="success" type="json"></result>        </action>    </package></struts>

ImageUtil.java :

public class ImageUtil {private static final String[] chars={"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};private static final int WIDTH=200;private static final int HEIGHT=100;private static final int SIZE=5;private static final int LINES=15;private static final int FONT_SIZE=45;public static Map<String,BufferedImage> getImage(){StringBuffer sb=new StringBuffer();BufferedImage image=new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_RGB);Graphics g=image.getGraphics();g.setColor(Color.LIGHT_GRAY);g.fillRect(0,0,WIDTH,HEIGHT);Random random=new Random();for(int i=1;i<=SIZE;i++){g.setColor(getRandomColor());int j=random.nextInt(chars.length);g.setFont(new Font(null,Font.BOLD,FONT_SIZE));g.drawString(chars[j],(i-1)*WIDTH/SIZE,HEIGHT/2);sb.append(chars[j]);}for(int i=0;i<LINES;i++){g.setColor(getRandomColor());g.drawLine(random.nextInt(WIDTH),random.nextInt(HEIGHT),random.nextInt(WIDTH),random.nextInt(HEIGHT));}Map<String,BufferedImage> map=new HashMap<String,BufferedImage>();map.put(sb.toString(),image);return map;}private static Color getRandomColor(){Random random=new Random();return new Color(random.nextInt(256),random.nextInt(256),random.nextInt(256));}}

ImageAction.java :

public class ImageAction extends ActionSupport {private InputStream image;public InputStream getImage() {return image;}public void setImage(InputStream image) {this.image = image;}public String execute() throws ImageFormatException, IOException{Map<String,BufferedImage> map=ImageUtil.getImage();String str=map.keySet().iterator().next();ActionContext.getContext().getSession().put("str",str);BufferedImage bi=map.get(str);ByteArrayOutputStream baos=new ByteArrayOutputStream();JPEGImageEncoder encoder=JPEGCodec.createJPEGEncoder(baos);encoder.encode(bi);image=new ByteArrayInputStream(baos.toByteArray());return "success";}}

ValidImageAction.java :

public class ValidImageAction extends ActionSupport {private String valiCode;private boolean ok;@JSON(serialize=false)public String getValiCode() {return valiCode;}public void setValiCode(String valiCode) {this.valiCode = valiCode;}public boolean isOk() {return ok;}public void setOk(boolean ok) {this.ok = ok;}public String execute(){String str=(String)ActionContext.getContext().getSession().get("str");if(str.equals(getValiCode())){ok=true;}else{ok=false;}return "success";}}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.