歡迎光臨我的小站,共同學習交流技術:http://www.luchg.com
完整代碼下載:http://download.csdn.net/detail/lc448986375/4603225
login.js:
//定義驗證碼控件
Ext.define('CheckCode',{
extend: 'Ext.form.field.Text',
alias: 'widget.checkcode',
inputTyle:'codefield',
codeUrl:Ext.BLANK_IMAGE_URL,
isLoader:true,
onRender:function(ct,position){
this.callParent(arguments);
this.codeEl = ct.createChild({ tag: 'img', src: Ext.BLANK_IMAGE_URL});
this.codeEl.addCls('x-form-code');
this.codeEl.on('click', this.loadCodeImg, this);
if (this.isLoader) this.loadCodeImg();
},
alignErrorIcon: function() {
this.errorIcon.alignTo(this.codeEl, 'tl-tr', [2, 0]);
},
//如果瀏覽器發現url不變,就認爲圖片沒有改變,就會使用緩存中的圖片,而不是重新向服務器請求,所以需要加一個參數,改變url
loadCodeImg: function() {
this.codeEl.set({ src: this.codeUrl + '?id=' + Math.random() });
}
});
Ext.onReady(
function(){
var checkcode = Ext.create('CheckCode',{
cls : 'key',
fieldLabel : '驗證碼',
name : 'CheckCode',
id : 'CheckCode',
allowBlank : false,
isLoader:true,
blankText : '驗證碼不能爲空',
codeUrl: 'getCode',
width : 150
});
var form = Ext.create(
'Ext.form.Panel',
{
frame:true,
title:'用戶登錄',
width:300,
height:170,
//渲染到頁面中的loginForm層中
renderTo:'loginForm',
//是否可以拖動
draggable:true,
//使buttons中的button居中顯示
buttonAlign:'center',
fieldDefaults:{
//居左
labelAlign:'center',
//寬度
labelWidth:50,
//anchor: '90%',
//錯誤提示顯示在一邊(side),還可以配置爲under、title、none
msgTarget: 'side'
},
items:[
{
xtype:'textfield',
fieldLabel:'用戶名',
name:'name',
//不允許爲空
allowBlank:false,
blankText:'用戶名不能爲空'
},
{
xtype:'textfield',
fieldLabel:'密 碼',
name:'password',
inputType:'password',
allowBlank:false,
blankText:'密碼不能爲空'
},
checkcode
],
buttons:[
{
text:'登錄',
width:80,
height:30,
handler:function(){
//獲取當前的表單form
var form = this.up('form').getForm();
//判斷否通過了表單驗證,如果不能空的爲空則不能提交
if(form.isValid()){
//alert("可以提交");
form.submit(
{
clientValidation:true,
waitMsg:'請稍候',
waitTitle:'正在驗證登錄',
url:'user_login',
success:function(form,action){
//登錄成功後的操作,這裏只是提示一下
Ext.MessageBox.show({
width:150,
title:"登錄成功",
buttons: Ext.MessageBox.OK,
msg:action.result.msg
})
},
failure:function(form,action){
Ext.MessageBox.show({
width:150,
title:"登錄失敗",
buttons: Ext.MessageBox.OK,
msg:action.result.msg
})
}
}
)
}
}
},
{
text:'取消',
width:80,
height:30,
handler:function(){
//點擊取消,關閉登錄窗口
var form = this.up('form');
form.close();
}
}
]
}
)
}
)
爲了佈局驗證碼位置,需要定義一個style.css
#CheckCode{ float:left;}
.x-form-code{width:75px;height:25px;vertical-align:middle;cursor:pointer; float:left; margin-left:7px;}
生成驗證碼的類:YanZhengMa.java:(英語學的不好,用拼音了。。。。)
package action;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Random;
import com.sun.image.codec.jpeg.ImageFormatException;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
public class YanZhengMa {
static String strCode = null;
public static final char[] CHARS = {'2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','J','K','L','M','N','P','Q','R','S','T','U','V','W','X','Y','Z'};
public static Random random = new Random();
//獲取六位隨機數
public static String getRandomString() {
StringBuffer buffer = new StringBuffer();
for (int i = 0;i<4;i++) {
buffer.append(CHARS[random.nextInt(CHARS.length)]);
}
strCode = buffer.toString();
System.out.println("4位隨機數:"+strCode);
return strCode;
}
//獲取隨機顏色
public static Color getRandomColor() {
return new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255));
}
//返回某顏色的反色
public static Color getReverseColor(Color c) {
return new Color(255 - c.getRed(), 255 - c.getGreen(), 255 - c.getBlue());
}
//創建圖片
public ByteArrayInputStream createImage() {
String randomString = getRandomString();//獲取隨機字符串
int width = 80;//設置圖片的寬度
int height = 30;//高度
Color color = getRandomColor();//獲取隨機顏色,作爲背景色
Color reverse = getReverseColor(color);//獲取反色,用於前景色
//創建一個彩色圖片
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = image.createGraphics();//獲取繪製對象
g.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 23));//設置字體
g.setColor(color);//設置顏色
g.fillRect(0, 0, width, height);//繪製背景
g.setColor(reverse);//設置顏色
g.drawString(randomString, 5, 23);
//最多繪製100個噪音點
for (int i = 0,n = random.nextInt(100); i < n; i++) {
g.drawRect(random.nextInt(width), random.nextInt(height), 1, 1);
}
//返回驗證碼圖片的流格式
ByteArrayInputStream bais = convertImageToStream(image);
return bais;
}
//將BufferedImage轉換成ByteArrayInputStream
private static ByteArrayInputStream convertImageToStream(BufferedImage image){
ByteArrayInputStream inputStream = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
JPEGImageEncoder jpeg = JPEGCodec.createJPEGEncoder(bos);
try {
jpeg.encode(image);
byte[] bts = bos.toByteArray();
inputStream = new ByteArrayInputStream(bts);
} catch (ImageFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return inputStream;
}
}
然後定義驗證碼請求的Action:YanZhengMaAction.java:
package action;
import java.io.ByteArrayInputStream;
import java.util.Map;
import org.apache.struts2.interceptor.SessionAware;
import com.opensymphony.xwork2.ActionSupport;
public class YanZhengMaAction extends ActionSupport implements SessionAware {
private ByteArrayInputStream bais;
YanZhengMa yanZhengMa = null;
String strCode = null;
private Map session;
public String getCode(){
yanZhengMa = new YanZhengMa();
bais = yanZhengMa.createImage();
strCode = yanZhengMa.strCode;
System.out.println("YanZhengMaAction>randomCode:"+strCode);
//放入session,在login的時候需要用到驗證
session.put("randomCode", strCode);
return SUCCESS;
}
public ByteArrayInputStream getBais() {
return bais;
}
public void setBais(ByteArrayInputStream bais) {
this.bais = bais;
}
public void setSession(Map<String, Object> arg0) {
this.session = arg0;
}
}
登錄驗證類:UserAction.java:
package action;
import java.io.ByteArrayInputStream;
import java.util.Map;
import org.apache.struts2.interceptor.SessionAware;
import com.opensymphony.xwork2.ActionSupport;
public class UserAction extends ActionSupport implements SessionAware {
//接收name,必須與js中的textfield的name相同,否則取不到值
private String name;
private String password;
//得到頁面傳來的驗證碼
private String CheckCode;
private Map session;
//定義一個msg變量,可用於存放錯誤信息,然後傳到前臺
//用於告訴前臺時候登錄成功
private boolean success;
public String login(){
//得到生成的驗證碼
String strCode = (String) session.get("randomCode");
System.out.println("UserAction>randomCode:"+strCode);
if("admin".equals(name) && "admin".equals(password) && CheckCode.toLowerCase().equals(strCode.toLowerCase())){
success = true;
}else{
success = false;
}
return SUCCESS;
}
效果圖: