分類  >  Web前端 >

Struts的Ext增刪節查應用範例

tags:    時間:2013-12-10 22:00:50
Struts的Ext增刪改查應用範例
index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>this is my first Extjs Demo...</title>
<!-- ext-all -->
<link rel="stylesheet" type="text/css" href="./extjs-3.0/resources/css/ext-all.css" mce_href="extjs-3.0/resources/css/ext-all.css" />
<!-- ext-base、ext-all、ext-lang-zh_CN-->
<mce:script type="text/javascript" src="./extjs-3.0/adapter/ext/ext-base.js" mce_src="extjs-3.0/adapter/ext/ext-base.js" charset="utf-8"></mce:script>
<mce:script type="text/javascript" src="./extjs-3.0/ext-all.js" mce_src="extjs-3.0/ext-all.js" charset="utf-8"></mce:script>
<mce:script type="text/javascript" src="./extjs-3.0/source/locale/ext-lang-zh_CN.js" mce_src="extjs-3.0/source/locale/ext-lang-zh_CN.js" charset="utf-8"></mce:script>
<mce:script type="text/javascript" src="./extjs-3.0/ext-all-debug.js" mce_src="extjs-3.0/ext-all-debug.js" charset="utf-8"></mce:script>
<mce:script type="text/javascript"><!--
Ext.onReady(function(){
Ext.BLANK_IMAGE_URL = 'extjs/resources/images/default/s.gif';
Ext.QuickTips.init();
//fields
var fields = Ext.data.Record.create([
{name: 'id', type: 'int' },
{name: 'name', type: 'string'},
{name: 'pass', type: 'string'},
{name: 'descn', type: 'string'}
]);
//model
var selectModel = new Ext.grid.CheckboxSelectionModel();
var model = new Ext.grid.ColumnModel([
new Ext.grid.RowNumberer(),
selectModel,
{header:'編號',dataIndex:'id',sortable:true},
{header:'名稱',dataIndex:'name',sortable:true},
{header:'密碼',dataIndex:'pass',sortable:true},
{header:'描述',dataIndex:'descn',sortable:true}
]);
//cm.defaultSortable = true;
//基於HttpProxy讀取Json數據的Factory
var store = new Ext.data.Store({
proxy: new Ext.data.HttpProxy({url:'userinfoAction.do?tag=getList',method:'GET'}),
reader: new Ext.data.JsonReader({
totalProperty: 'totalProperty',
root: 'root'
}, fields)
});
//創建工具欄組件
var toolbar = new Ext.Toolbar([
{text : 'add',iconCls:'add',handler : showAdd},
{text : 'modify',iconCls:'option',handler : showModify},
{text : 'delete',iconCls:'remove',handler : showDelete}
]);
//grid
var grid = new Ext.grid.GridPanel({
el: 'grid',
title: 'the Jsp with a JSON...',
ds: store,
cm: model,
sm: selectModel,
width:600,
height:480,
autoHeight: true,
viewConfig: {
forceFit:true
},
bbar: new Ext.PagingToolbar({
pageSize: 10,
store: store,
displayInfo: true,
displayMsg: '顯示第 {0} 條到 {1} 條記錄,一共 {2} 條',
emptyMsg: "沒有記錄"
}),
tbar: toolbar
});
grid.render();//渲染表格
store.load({params:{start:0, limit:10}});
//提交表單數據
function submitForm(){
//判斷當前執行的提交操作,isAdd為true表示執行新增操作,false表示執行修改操作
if(theForm.isAdd){
//新增信息
theForm.form.submit({
clientValidation:true,//進行客戶端驗證
waitMsg : '正在提交數據請稍後...',//提示信息
waitTitle : '提示',//標題
url : 'userinfoAction.do?tag=addObject',//請求的url地址
method:'POST',//請求方式
success:function(form,action){//載入成功的處理函數
win.hide();
//updateBookList(action.result.bookTypeId);
Ext.Msg.alert('提示','新增信息成功');
},
failure:function(form,action){//載入失敗的處理函數
Ext.Msg.alert('提示','新增信息失敗');
}
});
}else{
//修改信息
theForm.form.submit({
clientValidation:true,//進行客戶端驗證
waitMsg : '正在提交數據請稍後...',//提示信息
waitTitle : '提示',//標題
url : 'userinfoAction.do?tag=modifyObject',//請求的url地址
method:'POST',//請求方式
success:function(form,action){//載入成功的處理函數
win.hide();
//updateBookList(action.result.bookTypeId);
Ext.Msg.alert('提示','修改信息成功');
},
failure:function(form,action){//載入失敗的處理函數
Ext.Msg.alert('提示','修改信息失敗');
}
});
}
}
//創建新增或修改信息的form表單
Ext.QuickTips.init();
Ext.form.Field.prototype.msgTarget = 'side';//統一指定錯誤信息提示方式
var theForm = new Ext.FormPanel({
labelSeparator : ":",
frame:true,
border:false,
items : [
{
xtype:'textfield',
width : 200,
allowBlank : false,
blankText : '昵稱不能為空',
name : 'name',
fieldLabel:'昵稱'
},{
xtype:'textfield',
width : 200,
name : 'pass',
fieldLabel:'密碼',
inputType:'password',
allowBlank : false,
blankText : '密碼不能為空'
},{
xtype:'textarea',
width : 200,
name : 'descn',
regex:/^[\s\S]{1,50}$/,
regexText:"相關說明請不要超過50個字元",
fieldLabel:'相關說明'
},
{
xtype:'hidden',
name : 'id'
}
],
buttons:[
{
text : '提交',
handler : submitForm
},{
text : '取消',
handler : function(){
win.hide();
}
}
]
});
//創建彈出窗口
var win = new Ext.Window({
layout:'fit',
width:380,
closeAction:'hide',
height:200,
resizable : false,
shadow : true,
modal :true,
closable:true,
bodyStyle:'padding:5 5 5 5',
animCollapse:true,
items:[theForm]
});
//打開添加面板
function showAdd(){
theForm.form.reset();
theForm.isAdd = true;
win.setTitle("新增信息");
win.show();
}
//打開修改面板
function showModify(){
var theList = getObjectIdList();
var num = theList.length;
if(num > 1){
Ext.MessageBox.alert("提示","每次只能修改一條信息。")
}else if(num == 1){
theForm.isAdd = false;
win.setTitle("修改信息");
win.show();
var theId = theList[0];
loadForm(theId);
}
}
//取得所選項
function getObjectIdList(){
var recs = grid.getSelectionModel().getSelections();
var list = [];
if(recs.length == 0){
Ext.MessageBox.alert('提示','請選擇要進行操作的信息 !');
}else{
for(var i = 0 ; i < recs.length ; i++){
var rec = recs[i];
list.push(rec.get('id'))
}
}
return list;
}
//載入表單數據
function loadForm(theId){
theForm.form.load({
waitMsg : '正在載入數據請稍後',//提示信息
waitTitle : '提示',//標題
url : 'userinfoAction.do?tag=getModifyObject',//請求的url地址
params : {id:theId},
method:'GET',//請求方式
success:function(form,action){//載入成功的處理函數
//Ext.Msg.alert('提示','數據載入成功');
},
failure:function(form,action){//載入失敗的處理函數
Ext.Msg.alert('提示','數據載入失敗');
}
});
}
//打開刪除面板
function showDelete(){
var theList = getObjectIdList();
var num = theList.length;
if(num > 1){
Ext.MessageBox.alert("提示","每次只能刪除一條信息。")
}else if(num == 1){
Ext.MessageBox.confirm("提示","您確定要刪除所選信息嗎?",function(btnId){
if(btnId == 'yes'){
var theId = theList[0];
deleteObject(theId);
}
})
}
}
//刪除信息
function deleteObject(theId){
var msgTip = Ext.MessageBox.show({
title:'提示',
width : 250,
msg:'正在刪除信息請稍後......'
});
Ext.Ajax.request({
url : 'userinfoAction.do?tag=deleteObject',
params : {id : theId},
method : 'POST',
success : function(response,options){
msgTip.hide();
var result = Ext.util.JSON.decode(response.responseText);
if(result.success){
//伺服器端數據成功刪除后,同步刪除客戶端列表中的數據
//var index = typeStore.find('id',theId);
//if(index != -1){
// var rec = typeStore.getAt(index)
// typeStore.remove(rec);
//}
Ext.Msg.alert('提示','刪除信息成功。');
}else{
Ext.Msg.alert('提示','已包含'+result.num+'本信息不能刪除!');
}
},
failure : function(response,options){
msgTip.hide();
Ext.Msg.alert('提示','刪除信息請求失敗!');
}
});
}
});
// --></mce:script>
</head>
<div id="grid" ></div>
</html>
?
UserAction.java
package com.extjs.web;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
public class UserAction extends DispatchAction {
//查詢所有信息
public ActionForward getList(ActionMapping mapping , ActionForm form ,HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int start = 0;
int limit = 10;
StringBuffer json = new StringBuffer();
try {
if(request.getParameter("start") != null){
start = Integer.parseInt(request.getParameter("start").toString());
limit = Integer.parseInt(request.getParameter("limit").toString());
}
} catch (NumberFormatException e) {
}finally{
json.append("{totalProperty:100,root:[");
for(int i = start;i<limit+start;i++)
{
if(i < limit+start-1)
{
json.append("{'id':'"+i+"','name':'name"+i +"','pass':'pass"+i+"','descn':'descn"+i+ "'},");
}else
{
json.append("{'id':'"+i+"','name':'name"+i +"','pass':'"+i+"','descn':'descn"+i+ "'} ]}");
}
}
response.setContentType("text/json;charset=UTF-8");
response.getWriter().write(json.toString());
response.getWriter().close();
}
System.out.println("getList start: "+start+" json: "+json.toString());
return null;
}
//添加信息
public ActionForward addObject(ActionMapping mapping , ActionForm form ,HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String msg = "";
try {
if(request.getParameter("name") != null){
String name = request.getParameter("name").toString();
String pass = request.getParameter("pass").toString();
String descn = request.getParameter("descn").toString();
if(true){
msg="{success:true,data:{name:'"+name+"',pass:'"+pass+"',descn:'"+descn+"'}}";
//成功時候的返回信息
}else{
msg="{success:false,errors:{rs:'name和descn不匹配,請重新輸入'}}";
//失敗時候的返回信息
}
response.setContentType("text/json;charset=UTF-8");
response.getWriter().write(msg);
}
} catch (NumberFormatException e) {
}finally{
response.getWriter().close();
}
System.out.println("addObject msg: "+msg);
return null;
}
//獲得修改信息
public ActionForward getModifyObject(ActionMapping mapping , ActionForm form ,HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String msg = "";
try {
if(request.getParameter("id") != null){
int id = Integer.parseInt(request.getParameter("id").toString());
if(true){
msg="{success:true,data:{id:'"+id+"',name:'name"+id+"',pass:'pass"+id+"',descn:'descn"+id+"'}}";
//成功時候的返回信息
}else{
msg="{success:false,errors:{rs:'name和descn不匹配,請重新輸入'}}";
//失敗時候的返回信息
}
response.setContentType("text/json;charset=UTF-8");
response.getWriter().write(msg);
}
} catch (NumberFormatException e) {
}finally{
response.getWriter().close();
}
System.out.println("getModifyObject msg: "+msg);
return null;
}
//修改信息
public ActionForward modifyObject(ActionMapping mapping , ActionForm form ,HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String msg = "";
try {
if(request.getParameter("id") != null){
int id = Integer.parseInt(request.getParameter("id").toString());
String name = request.getParameter("name").toString();
String pass = request.getParameter("pass").toString();
String descn = request.getParameter("descn").toString();
if(true){
msg="{success:true,data:{id:'"+id+"',name:'"+name+"',pass:'"+pass+"',descn:'"+descn+"'}}";
//成功時候的返回信息
}else{
msg="{success:false,errors:{rs:'name和descn不匹配,請重新輸入'}}";
//失敗時候的返回信息
}
response.setContentType("text/json;charset=UTF-8");
response.getWriter().write(msg);
}
} catch (NumberFormatException e) {
}finally{
response.getWriter().close();
}
System.out.println("modifyObject msg: "+msg);
return null;
}
//刪除信息
public ActionForward deleteObject(ActionMapping mapping , ActionForm form ,HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String msg = "";
try {
if(request.getParameter("id") != null){
int id = Integer.parseInt(request.getParameter("id").toString());
if(id != 0){
msg="{success:true,data:{id:'"+id+"'}}";
//成功時候的返回信息
}else{
msg="{success:false,errors:{rs:'id不匹配,請重新輸入'}}";
//失敗時候的返回信息
}
response.setContentType("text/json;charset=UTF-8");
response.getWriter().write(msg);
}
} catch (NumberFormatException e) {
}finally{
response.getWriter().close();
}
System.out.println("deleteObject msg: "+msg);
return null;
}
}

推薦閱讀文章

Bookmark the permalink ,來源:互聯網