最近要用到ext,所以用ext和struts2做了一个小实例,包含登陆和数据显示功能。通过一个form提交数据到后台,后台判断成功后传递数据到前台grid
Grid.js代码如下:


1、搭建开发环境
开发工具我用的是MyEclipse 6.5,Tomcat 6.0
导入工程所需要jar包,struts2所需的5个jar包,ext和java传递数据用的json jar包,如下图所示

在WebRoot下的web.xml添加struts2的filter,web.xml内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>login.html</welcome-file>
</welcome-file-list>
</web-app>
2、登陆判断
编写登陆页面代码,一个form,里面两个输入框,提交数据到后台action进行判断,并根据返回信息进行下一步操作
login.html代码:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>login</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">
-->
<link rel="stylesheet" type="text/css" href="Ext/resources/css/ext-all.css"/>
<!-- GC -->
<!-- LIBS -->
<script type="text/javascript" src="Ext/adapter/ext/ext-base.js"></script>
<!-- ENDLIBS -->
<script type="text/javascript" src="Ext/ext-all.js"></script>
<script type="text/javascript" src="login.js"></script>
</head>
<body>
</body>
</html>
login.js代码
Ext.onReady(function(){
Ext.QuickTips.init();
Ext.form.Field.prototype.msgTarget = 'side';
var loginForm = new Ext.form.FormPanel({
frame: true,
keys: [{
key:[13],
fn: function() {
if(loginForm.getForm().isValid()) {
login();
}
}
}],
items: [{
xtype: 'textfield',
fieldLabel: 'name',
allowBlank: false,
blankText: 'input the user name',
id: 'userId'
},{
xtype: 'textfield',
inputType: 'password',
fieldLabel: 'password',
allowBlank: false,
blankText: 'input the password',
id: 'userPas'
}],
waitMsgTarget:true
});
var win = new Ext.Window({
title: 'Login',
layout: 'fit',
width: 400,
height: 200,
closable: false,
resizable: false,
draggable: true,
items: [
loginForm
],
buttonAlign: 'center',
buttons: [{
text: 'Login',
id: 'login',
handler: function() {
if(loginForm.getForm().isValid()) {
login();
}
}
},{
text: 'Reset',
id: 'reset',
handler: function() {
loginForm.getForm().reset();
}
}]
});
win.show();
function login() {
Ext.getCmp('login').disable();
Ext.getCmp('reset').disable();
loginForm.getForm().submit({
url: 'loginAction.action', //提交的action
//判断成功后执行
success:function(form,action){
Ext.Msg.alert("login succeed",action.result.message);
window.location="Grid.html";
},
//判断失败后执行
failure: function(form, action) {
Ext.getCmp('login').enable();
Ext.getCmp('reset').enable();
Ext.Msg.alert("password wrong",action.result.message);
loginForm.getForm().reset();
},
waitMsg: 'please wait......'
});
}
});登陆action,在src下建com.test包,
package com.test;
import java.util.List;
import com.opensymphony.xwork2.ActionSupport;
public class LoginAction extends ActionSupport {
private static final long serialVersionUID = 1L;
private String userId; //对应login.js里的userId
private String userPas; //对应login.js里的userPas
private boolean success; //返回判断信息,true则会执行login.js里的success里的函数
private String message; //返回提示信息
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserPas() {
return userPas;
}
public void setUserPas(String userPas) {
this.userPas = userPas;
}
public String loginCheck() throws Exception {
if(userId.equals("123")&&userPas.equals("123")){
this.success=true;
this.message="登陆成功,欢迎进入!";
}else{
this.success=false;
this.message="密码或用户名错误";
}
return SUCCESS;
}
}在src下建struts.xml文件,文件内容如下<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="loginAction" extends="json-default" namespace="/">
<action name="loginAction" class="com.test.LoginAction" method="loginCheck">
<result type="json"/>
</action>
<action name="gridAction" class="com.test.GridAction" method="execute">
<result type="json"/>
</action>
</package>
</struts>注意这个地方extends后是json-default,result type为json 3、grid显示数据
Grid.html代码如下
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Test</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">
-->
<link rel="stylesheet" type="text/css" href="Ext/resources/css/ext-all.css" />
<script type="text/javascript" src="Ext/adapter/ext/ext-base.js"></script>
<script type="text/javascript" src="Ext/ext-all.js"></script>
<script type="text/javascript" src="Grid.js"></script>
</head>
<body>
<div id="grid"></div>
</body>
</html>Grid.js代码如下:
Ext.onReady(function(){
// NOTE: This is an example showing simple state management. During development,
// it is generally best to disable state management as dynamically-generated ids
// can change across page loads, leading to unpredictable results. The developer
// should ensure that stable state ids are set for stateful components in real apps.
Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
/**
* Custom function used for column renderer
* @param {Object} val
*/
function change(val){
if(val > 0){
return '<span style="color:green;">' + val + '</span>';
}else if(val < 0){
return '<span style="color:red;">' + val + '</span>';
}
return val;
}
/**
* Custom function used for column renderer
* @param {Object} val
*/
function pctChange(val){
if(val > 0){
return '<span style="color:green;">' + val + '%</span>';
}else if(val < 0){
return '<span style="color:red;">' + val + '%</span>';
}
return val;
}
var store = new Ext.data.Store({
proxy: new Ext.data.HttpProxy({url:'gridAction.action'}),//请求数据的action
reader: new Ext.data.JsonReader({
root: 'products', //对应传递数据的变量名
successProperty :'success'
}, [
{name: 'company',mapping:'company',type:'string'},//mapping后卫后台bean对象的属性,name为store设的属性
{name: 'price',mapping:'price',type:'int'},
{name: 'change',mapping:'change',type:'int'},
{name: 'pct',mapping:'pct',type:'int'},
])
});
// manually load data
store.load();//加载数据
// create the Grid
var grid = new Ext.grid.GridPanel({
store: store,
columns: [
{id:'company',header: 'Company', width: 160, sortable: true, dataIndex: 'company'},
{header: 'Price', width: 75, sortable: true, renderer: 'usMoney', dataIndex: 'price'},
{header: 'Change', width: 75, sortable: true, renderer: change, dataIndex: 'change'},
{header: '% Change', width: 75, sortable: true, renderer: pctChange, dataIndex: 'pct'}
],
stripeRows: true,
autoExpandColumn: 'company',
height: 350,
width: 600,
title: 'Array Grid',
// config options for stateful behavior
stateful: true,
stateId: 'grid'
});
// render the grid to the specified div in the page
grid.render('grid');
});这里传递数据是把后台的bean对象传递到前台的store里,store的列属性和bean的属性相对应
后台action,代码如下
package com.test;
import java.util.ArrayList;
import java.util.List;
import com.opensymphony.xwork2.ActionSupport;
public class GridAction extends ActionSupport {
private static final long serialVersionUID = 1L;
private List<Product> products; //对应grid.js里的root
private boolean success;
private String message;
public List<Product> getProducts() {
return products;
}
public void setProducts(List<Product> products) {
this.products = products;
}
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String execute() throws Exception {
List<Product> list=new ArrayList<Product>();
for(int i=0;i<10;i++){
Product pro=new Product();
pro.setCompany("hhu");
pro.setChange(1);
pro.setPrice(1);
pro.setPct(1);
list.add(pro);
}
setProducts(list);
this.success=true;
return SUCCESS;
}
}然后在struts.xml里加入action Product代码如下,
package com.test;
public class Product {
private String company;
private int price;
private int change;
private int pct;
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public int getChange() {
return change;
}
public void setChange(int change) {
this.change = change;
}
public int getPct() {
return pct;
}
public void setPct(int pct) {
this.pct = pct;
}
}工程结构如下:

部署工程,可以测试了
很多东西没有深究,所有就写到这。
版权声明:本文为liyang36939原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。