Extjs3综合应用(待续v4...初版)
最近又要搞界面了。郁闷啊。
Extjs3.1+spring3+ibatis3+struts2,东西太多了。
把自己写的一些例跟大家分享一下。
效果图:
Extjs界面结构
<%@ page contentType="text/html; charset=UTF-8" errorPage="../errorpage.jsp"%>
<%@include file="../../inc/expiresinc.jsp"%>
<html>
<head>
<title>模板页面</title>
<script type="text/javascript">
extjs 代码.显示时要设置infodiv
</script>
</head>
<body><div id="infodiv" style="width:100%;height:100%;"></div></body>
</html>
导入Extjs 那些代码这不写了。
一个简单的 Extjs 界面就这样了:
<%@ page contentType="text/html; charset=UTF-8" errorPage="../errorpage.jsp"%>
<%@include file="../../inc/expiresinc.jsp"%>
<html>
<head>
<title>模板页面</title>
<script type="text/javascript">
var panel_permissiondiv = new Ext.Panel({
renderTo : 'infodiv',
width : Ext.get("infodiv").getWidth(),
height : Ext.get("infodiv").getHeight(),
border : false,
layout : 'border',
tbar : ['->', {
text : 'TEXT',
iconCls : 'icon-add',
xtype : 'easyButton',
tooltip : 'TEXT'
}, '-', {
text : 'TEXT',
iconCls : 'icon-add',
xtype : 'easyButton',
tooltip : 'TEXT'
}],
items : [from_permission, grid_permission]
});
</script>
</head>
<body><div id="permissiondiv" style="width:100%;height:100%;"></div></body>
</html>
上面的“items : [from_permission, grid_permission]”,是界面加载的另的无素。稍后会写到。
再给个完整一点的页面吧:
<%@ page contentType="text/html; charset=UTF-8" errorPage="../errorpage.jsp"%>
<%@include file="../../inc/expiresinc.jsp"%>
<html>
<head>
<title>模板页面</title>
<script type="text/javascript">
var storeLoadMask = new Ext.LoadMask(Ext.getBody(), {
msg : "正在加载数据,请等待..."
});
storeLoadMask.show();
var panel = Ext.getCmp('center-tab-panel');
var from_subscriberpk = new Ext.FormPanel({
labelAlign : 'left',
labelWidth : 140,
frame : true,
title : '查询',
region : 'north',
collapseMode : 'mini',
split : true,
height : 140,
minSize : 120,
maxSize : 200,
split : true,
collapsible : true,
margins : '5 5 0 5',
items : [{
layout : 'column',
items : [{
columnWidth : .4,
layout : 'form',
defaults : {
anchor : '93%'
},
items : [{
xtype : 'textfield',
fieldLabel : 'TEXT',
name : ''
}]
}, {
columnWidth : .4,
layout : 'form',
defaults : {
anchor : '93%'
},
items : [{
xtype : 'textfield',
fieldLabel : 'TEXT',
name : ''
}]
}]
}, {
layout : 'column',
items : [{
columnWidth : .4,
layout : 'form',
defaults : {
anchor : '93%'
},
items : [{
xtype : 'datefield',
fieldLabel : 'TEXT',
name : ''
}]
}, {
columnWidth : .4,
layout : 'form',
defaults : {
anchor : '93%'
},
items : [{
xtype : 'datefield',
fieldLabel : 'TEXT',
name : ''
}]
}, {
columnWidth : .2,
layout : 'table',
items : [{
xtype : 'button',
width : '70',
// iconCls : 'icon-add',
xtype : 'easyButton',
text : '查 询'
}, {
xtype : 'button',
width : '70',
//iconCls : 'icon-add',
xtype : 'easyButton',
style : 'margin-left: 5px',
text : '清 空'
}]
}]
}]
});
// ------------------Grid 部分-----------------------
function rendercz(value, cellmeta, record, rowIndex, columnIndex, store) {
return "<img src = 'images/edit.gif' title='操作' align='center' onclick='tab_subscriberpk(\""
+ record.data["region"]+"\",\""+ record.data["pwd"]+"\")' />";
};
function rowdblclickfn(grid, rowIndex, e){// 双击事件
var row = grid_subscriberpk.store.getById(grid.store.data.items[rowIndex].id);
tab_subscriberpk(row.get("region"),row.get("pwd"));
}
function tab_subscriberpk(id,code){// 打开TAB
var url = 'MyJsp.jsp';
var tab = panel.findById('tab-'+id);
if (tab == undefined){
tab = panel.add({
id:'tab-'+id,
title: code,
iconCls: 'icon-nav-p1',
closable:true,// 通过html载入目标页
// html:'<iframe id="'+id+'" scrolling="auto"
// frameborder="0" width="100%" height="100%"
// src="'+url+'"></iframe>'
autoLoad: url
});
panel.setActiveTab(tab);
}else{
panel.activate(tab)
}
}
function getrecordarry(records,field) {
var result = [];
for(var i = 0; i < records.length; i++) {
result.push(records[i].get(field));
}
return result;
}
// 删除操作
function deletesubscriberpk(){
var records = grid_subscriberpk.getSelectionModel().getSelections();// 删除多行
if (records) {
Ext.MessageBox.confirm('确认删除','确定要删除所选记录?',function(btn){
if (btn == 'yes'){
Ext.Ajax.request({
url:'SubscriberPk/extdelete.do?ids='+getrecordarry(records, 'subsid'),
method:'POST',
success:function(response){
var data = Ext.util.JSON.decode(response.responseText);
if (data.success == true){
Ext.Msg.show({title:'成功提示',msg:data.msg,buttons:Ext.Msg.OK,icon: Ext.MessageBox.INFO});
ds_subscriberpk.load();
}
else{
Ext.MessageBox.alert('警告',data.msg);
}
},scope:this
});
}
},this);
}else {
Ext.Msg.show({title:'提示信息',msg:'请选择需删除的记录!',buttons:Ext.Msg.OK,icon:Ext.Msg.INFO});
}
}
var fom_addsubscriberpk =new Ext.FormPanel({
labelWidth:100,
labelAlign:'right',
frame:true,
autoScroll:true,// 滚动条
items:[{
xtype:'panel',
layout:'column',
width:400,
defaults:{border:false}
}
,{xtype:'hidden',fieldLabel:'subsid',name:'subsid',width:288}
,{xtype:'textfield',fieldLabel:'region',name:'region',width:288}
,{xtype:'textfield',fieldLabel:'pwd',name:'pwd',width:288}
,{xtype:'textfield',fieldLabel:'createdate',name:'createdate',width:288}
,{xtype:'textfield',fieldLabel:'score',name:'score',width:288}
,{xtype:'textfield',fieldLabel:'startdate',name:'startdate',width:288}
,{xtype:'textfield',fieldLabel:'invaliddate',name:'invaliddate',width:288}
,{xtype:'textfield',fieldLabel:'substype',name:'substype',width:288}
,{xtype:'textfield',fieldLabel:'active',name:'active',width:288}
,{xtype:'textfield',fieldLabel:'status',name:'status',width:288}
],
buttons:[{
text:'保存',
handler:function(){// 保存操作
if (fom_addsubscriberpk.form.isValid() == false){
return;
}
fom_addsubscriberpk.form.submit({
url:'SubscriberPk/extsave.do',
success:function(form,action){
Ext.MessageBox.alert('警告',action.result.msg);
win_addsubscriberpk.hide();
grid_subscriberpk.getStore().reload();
},
scope:this,
failure:function(form,action){
Ext.MessageBox.alert('警告',action.result.msg);
}
})
}
},{
text:'取消',
handler:function(){win_addsubscriberpk.hide();}
}]
}
);
var win_addsubscriberpk = new Ext.Window(
{title:'添加记录',iconCls : 'icon-add',width:535,height:400,border:false,resizable:false,autoHeight:true,modal:true,closeAction:'hide',
items:[fom_addsubscriberpk]
});
var fom_upsubscriberpk =new Ext.FormPanel({
labelWidth:100,
labelAlign:'right',
frame:true,
autoScroll:true,// 滚动条
items:[{
xtype:'panel',
layout:'column',
width:400,
defaults:{border:false}
}
,{xtype:'hidden',fieldLabel:'subsid',name:'subsid',width:288}
,{xtype:'textfield',fieldLabel:'region',name:'region',width:288}
,{xtype:'textfield',fieldLabel:'pwd',name:'pwd',width:288}
,{xtype:'textfield',fieldLabel:'createdate',name:'createdate',width:288}
,{xtype:'textfield',fieldLabel:'score',name:'score',width:288}
,{xtype:'textfield',fieldLabel:'startdate',name:'startdate',width:288}
,{xtype:'textfield',fieldLabel:'invaliddate',name:'invaliddate',width:288}
,{xtype:'textfield',fieldLabel:'substype',name:'substype',width:288}
,{xtype:'textfield',fieldLabel:'active',name:'active',width:288}
,{xtype:'textfield',fieldLabel:'status',name:'status',width:288}
],
buttons:[{
text:'修改',
handler:function(){
if (fom_upsubscriberpk.form.isValid() == false){
return;
}
fom_upsubscriberpk.form.submit({
url:'SubscriberPk/extupdate.do',
success:function(form,action){
Ext.MessageBox.alert('警告',action.result.msg);
win_upsubscriberpk.hide();
grid_subscriberpk.getStore().reload();
},
scope:this,
failure:function(form,action){
Ext.MessageBox.alert('警告',action.result.msg);
}
})
}
},{
text:'取消',
handler:function(){win_upsubscriberpk.hide();}
}]
}
);
var win_upsubscriberpk = new Ext.Window(
{title:'修改记录',iconCls : 'icon-editp',width:535,height:400,border:false,resizable:false,autoHeight:true,modal:true,closeAction:'hide',
items:[fom_upsubscriberpk]});
function upsubscriberpk(){
var records = grid_subscriberpk.getSelectionModel().getSelections();
if (records.length==0) {
Ext.Msg.alert("提示", "请选择要修改的记录");
return;
}
if (records.length!=1) {
Ext.Msg.alert("提示", "请只选择1条要修改的记录");
return;
}
fom_upsubscriberpk.form.loadRecord(records[0]);
win_upsubscriberpk.show();
}
sm = new Ext.grid.CheckboxSelectionModel();
ds_subscriberpk =new Ext.data.Store({
url:'SubscriberPk/extlist.do',
reader:new Ext.data.JsonReader({
root:'list',
totalProperty:'totalSize',
id:'id'
},
['subsid','region','pwd','createdate','score','startdate','invaliddate','substype','active','status','cz']),
baseParams:{limit:10},
remoteSort:true
});
cm_subscriberpk = new Ext.grid.ColumnModel([
sm,new Ext.grid.RowNumberer()
,{header:'region',width:100,sortable:true,dataIndex:'region'}
,{header:'pwd',width:100,sortable:true,dataIndex:'pwd'}
,{header:'createdate',width:100,sortable:true,dataIndex:'createdate'}
,{header:'score',width:100,sortable:true,dataIndex:'score'}
,{header:'startdate',width:100,sortable:true,dataIndex:'startdate'}
,{header:'invaliddate',width:100,sortable:true,dataIndex:'invaliddate'}
,{header:'substype',width:100,sortable:true,dataIndex:'substype'}
,{header:'active',width:100,sortable:true,dataIndex:'active'}
,{header:'status',width:100,sortable:true,dataIndex:'status'}
,{header : '操作',width:40,dataIndex :'cz',renderer : rendercz}
]);
cm_subscriberpk.defaultSortable = true;
grid_subscriberpk= new Ext.grid.EditorGridPanel({
margins : '0 5 5 5',
store : ds_subscriberpk,
sm : sm,
cm : cm_subscriberpk,
stripeRows : true,
viewConfig : {
forceFit : true
},
loadMask : {
msg : '正在加载数据,请等待...'
},
region : 'center',
// clicksToEdit : 1,
trackMouseOver : true,
tbar : [{
text : '添加',
iconCls : 'icon-add',
handler : function() {win_addsubscriberpk.show()}
},'-',{
text:'删除',
iconCls:'icon-dela',
handler : function() {deletesubscriberpk()}
},'-',{
text:'修改',
iconCls:'icon-editp',
handler : function() {upsubscriberpk()}
},'-',{
text : '刷新',
iconCls : 'icon-ref',
handler : function() {
ds_subscriberpk.load();
}
},'->','<span style="color:blue;">双击表格可查看 </span>'],
bbar : new Ext.PagingToolbar({
pageSize:10,
store:ds_subscriberpk,
displayInfo:true
})
});
grid_subscriberpk.addListener('rowdblclick', rowdblclickfn);
ds_subscriberpk.load({
params:{start:0},
callback:function(r, options, success){
if (success) {
storeLoadMask.hide();
}
}
});
var panel_subscriberpkdiv = new Ext.Panel({
renderTo : 'subscriberpkdiv',
width : Ext.get("subscriberpkdiv").getWidth(),
height : Ext.get("subscriberpkdiv").getHeight(),
border : false,
layout : 'border',
tbar : ['->', {
text : 'TEXT',
iconCls : 'icon-add',
xtype : 'easyButton',
tooltip : 'TEXT'
}, '-', {
text : 'TEXT',
iconCls : 'icon-add',
xtype : 'easyButton',
tooltip : 'TEXT'
}],
items : [from_subscriberpk, grid_subscriberpk]
});
</script>
</head>
<body><div id="subscriberpkdiv" style="width:100%;height:100%;"></div></body>
</html>
页面部门基本上是这样了。一般的增删改查操作,上面都有了。
明天再把后台实现整理下。
数据表结构:
表:T_BAOTEST_INFO
-- Create table create table T_BAOTEST_INFO ( ID_ NUMBER not null, NAME_ VARCHAR2(20), EXPLAIN_ VARCHAR2(100), URL_ VARCHAR2(30) ) tablespace TBS_KINGTER pctfree 10 initrans 1 maxtrans 255 storage ( initial 64K minextents 1 maxextents unlimited ); -- Add comments to the columns comment on column T_BAOTEST_INFO.ID_ is '序列'; comment on column T_BAOTEST_INFO.NAME_ is '工程名称'; comment on column T_BAOTEST_INFO.EXPLAIN_ is '说明'; comment on column T_BAOTEST_INFO.URL_ is '路径'; -- Create/Recreate primary, unique and foreign key constraints alter table T_BAOTEST_INFO add constraint T_BAOTEST_KEY_ID primary key (ID_) deferrable initially deferred; -- Create/Recreate indexes create index T_BAO_TEST_INDEX_ID on T_BAOTEST_INFO (ID_) tablespace TBS_KINGTER pctfree 10 initrans 2 maxtrans 255 storage ( initial 64K minextents 1 maxextents unlimited ) compress reverse;
序列:SEQG_BAOTEST_ID
-- Create sequence
create sequence SEQG_BAOTEST_ID
minvalue 1
maxvalue 999999
start with 1
increment by 1
cache 20
cycle
order;
功能实现Java代码:
DAO数据类:
package com.mylink.mipbs.model;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import java.util.*;
import javacommon.base.*;
import javacommon.util.*;
import cn.org.rapid_framework.util.*;
import cn.org.rapid_framework.web.util.*;
import cn.org.rapid_framework.page.*;
import cn.org.rapid_framework.page.impl.*;
import com.mylink.mipbs.model.*;
import com.mylink.mipbs.dao.*;
import com.mylink.mipbs.service.impl.*;
import com.mylink.mipbs.service.*;
public class Baotest extends BaseEntity {
//alias
public static final String TABLE_ALIAS = "Baotest";
public static final String ALIAS_ID_ = "序列";
public static final String ALIAS_NAME_ = "工程名称";
public static final String ALIAS_EXPLAIN_ = "说明";
public static final String ALIAS_URL_ = "路径";
//date formats
public static final String FORMAT_BIRTHDAY_ = DATE_TIME_FORMAT;
//columns START
private java.lang.Long id;
private java.lang.String name;
private java.lang.String explain;
private java.lang.String url;
//columns END
public Baotest(){
}
public Baotest(
java.lang.Long id
){
this.id = id;
}
public java.lang.Long getId() {
return id;
}
public void setId(java.lang.Long id) {
this.id = id;
}
public java.lang.String getName() {
return name;
}
public void setName(java.lang.String name) {
this.name = name;
}
public java.lang.String getExplain() {
return explain;
}
public void setExplain(java.lang.String explain) {
this.explain = explain;
}
public java.lang.String getUrl() {
return url;
}
public void setUrl(java.lang.String url) {
this.url = url;
}
public String toString() {
return new ToStringBuilder(this)
.append("id",getId())
.append("name",getName())
.append("explain",getExplain())
.append("url",getUrl())
.toString();
}
public int hashCode() {
return 1;
}
public boolean equals(Object obj) {
if(obj instanceof CpHzzl == false) return false;
if(this == obj) return true;
CpHzzl other = (CpHzzl)obj;
return true;
}
}
IBATIS3 sql 配置文件:
位置:com/mylink/mipbs/model/mapper
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN" "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd"> <mapper namespace="Baotest"> <resultMap id="BaotestResult" type="com.mylink.mipbs.model.Baotest"> <result property="id" column="ID_" /> <result property="name" column="NAME_" /> <result property="explain" column="EXPLAIN_" /> <result property="url" column="URL_" /> </resultMap> <!-- 用于select查询公用抽取的列 --> <sql id="dictionaryColumns"> <![CDATA[ ID_ , NAME_ , EXPLAIN_ , URL_ ]]> </sql> <!-- useGeneratedKeys="true" keyProperty="xxx" for sqlserver and mysql --> <insert id="insert" parameterType="com.mylink.mipbs.model.Baotest" > <selectKey keyProperty="id" resultType="java.lang.Long" order="BEFORE"> select SEQG_BAOTEST_INFO_ID.nextval as id from dual </selectKey> <![CDATA[ INSERT INTO TG_DICTIONARY_INFO ( ID_ , NAME_ , EXPLAIN_, URL_ ) VALUES ( #{id,jdbcType=DECIMAL} , #{name,jdbcType=VARCHAR} , #{explain,jdbcType=VARCHAR} , #{url,jdbcType=VARCHAR} ) ]]> <!-- oracle: order="BEFORE" SELECT sequenceName.nextval AS ID FROM DUAL DB2: order="BEFORE"" values nextval for sequenceName <selectKey resultType="java.lang.Long" order="BEFORE" keyProperty="userId"> SELECT sequenceName.nextval AS ID FROM DUAL </selectKey> --> </insert> <update id="update" parameterType="com.mylink.mipbs.model.Baotest"> <![CDATA[ UPDATE TG_Baotest_INFO SET NAME_ = #{name,jdbcType=VARCHAR} , EXPLAIN_ = #{explain,jdbcType=VARCHAR} , URL_ = #{url,jdbcType=VARCHAR} WHERE ID_ = #{id} ]]> </update> <delete id="delete" parameterType="java.lang.Long"> <![CDATA[ delete from TG_Baotest_INFO where ID_ = #{id} ]]> </delete> <select id="getById" parameterType="java.lang.Long" resultMap="BaotestResult"> select <include refid="BaotestColumns" /> <![CDATA[ from TG_Baotest_INFO where ID_ = #{id} ]]> </select> <sql id="BaotestDynamicWhere"> <!-- ognl访问静态方法的表达式 为@[email protected](args),以下为调用rapid中的Ognl.isNotEmpty()方法,还有其它方法如isNotBlank()可以使用,具体请查看Ognl类 --> <where> <if test="@[email protected](id)"> and ID_ = #{id} </if> <if test="@[email protected](name)"> and NAME_ = #{name} </if> </where> </sql> <select id="count" resultType="long"> select count(*) from T_Baotest_INFO <include refid="BaotestDynamicWhere"/> </select> <!-- 分页查询已经使用Dialect进行分页,也可以不使用Dialect直接编写分页 因为分页查询将传 offset,pageSize,lastRows 三个参数,不同的数据库可以根于此三个参数属性应用不同的分页实现 --> <select id="pageSelect" resultMap="BaotestResult"> select <include refid="BaotestColumns" /> from T_Baotest_INFO <include refid="BaotestDynamicWhere"/> <if test="@[email protected](sortColumns)"> ORDER BY ${sortColumns} </if> </select> </mapper>
ibatis接口定义
package com.mylink.mipbs.service; import java.util.Map; import cn.org.rapid_framework.page.Page; import cn.org.rapid_framework.page.PageRequest; import com.mylink.mipbs.model.*; /** * ibatis接口定义 * @author Administrator * */ public interface BaotestManager { /**按ID查询数据*/ Baotest getById(java.lang.Long id); /**保存数据*/ void save(Baotest u); /**修改数据*/ void update(Baotest u); /**删除数据*/ void removeById (java.lang.Long id); /**分页查询数据*/ Page findByPageRequest(PageRequest<Map> q); }
IBATIS3 DAO
package com.mylink.mipbs.dao;
import javacommon.base.BaseIbatis3Dao;
import org.springframework.stereotype.Component;
import cn.org.rapid_framework.page.Page;
import cn.org.rapid_framework.page.PageRequest;
import com.mylink.mipbs.model.Baotest;
@Component
public class BaotestDao extends BaseIbatis3Dao<Baotest,java.lang.Long>{
public Class getEntityClass() {
return Baotest.class;
}
public void saveOrUpdate(Baotest entity) {
if(entity.getId() == null)
save(entity);
else
update(entity);
}
public Page findByPageRequest(PageRequest pageRequest) {
return pageQuery("Baotest.pageSelect",pageRequest);
}
}
IBATIS3 实现类:
package com.mylink.mipbs.service.impl;
import java.util.Map;
import javacommon.base.BaseManager;
import javacommon.base.EntityDao;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import cn.org.rapid_framework.page.Page;
import cn.org.rapid_framework.page.PageRequest;
import com.mylink.mipbs.dao.BaotestDao;
import com.mylink.mipbs.model.Baotest;
import com.mylink.mipbs.service.BaotestManager;
@Component("baotestManager")
@Transactional
public class BaotestManagerImpl extends BaseManager<Baotest, java.lang.Long>
implements BaotestManager {
private BaotestDao baotestDao;
/** 增加setXXXX()方法,spring就可以通过autowire自动设置对象属性 */
public void setCpHzzlDao(BaotestDao dao) {
this.baotestDao = dao;
}
public EntityDao getEntityDao() {
return this.baotestDao;
}
@Transactional(readOnly = true)
public Page findByPageRequest(PageRequest pr) {
return baotestDao.findByPageRequest(pr);
}
}
事件处理类
package com.mylink.mipbs.action;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javacommon.util.extjs.ExtJsPageHelper;
import javacommon.util.extjs.ListRange;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang.StringUtils;
import cn.org.rapid_framework.page.Page;
import cn.org.rapid_framework.page.PageRequest;
import com.mylink.mipbs.model.User;
import com.opensymphony.xwork2.Preparable;
import com.opensymphony.xwork2.ModelDriven;
import static javacommon.util.extjs.Struts2JsonHelper.*;
import java.util.*;
import javacommon.base.*;
import javacommon.util.*;
import cn.org.rapid_framework.util.*;
import cn.org.rapid_framework.web.util.*;
import cn.org.rapid_framework.page.*;
import cn.org.rapid_framework.page.impl.*;
import com.mylink.mipbs.model.*;
import com.mylink.mipbs.dao.*;
import com.mylink.mipbs.service.impl.*;
import com.mylink.mipbs.service.*;
/**
* 事件处理类
* @author Administrator
*
*/
public class BaotestAction extends BaseStruts2Action implements Preparable,ModelDriven{
//默认多列排序,example: username desc,createTime asc
protected static final String DEFAULT_SORT_COLUMNS = null;
//forward paths
/**对应到处理页面*/
protected static final String QUERY_JSP = "/pages/Baotest/query.jsp";
protected static final String LIST_JSP= "/pages/Baotest/list.jsp";
protected static final String CREATE_JSP = "/pages/Baotest/create.jsp";
protected static final String EDIT_JSP = "/pages/Baotest/edit.jsp";
protected static final String SHOW_JSP = "/pages/Baotest/show.jsp";
//redirect paths,startWith: !
protected static final String LIST_ACTION = "!/pages/Baotest/list.do";
private BaotestManager BaotestManager;
private Baotest Baotest;
java.lang.Long id = null;
private String[] items;
public void prepare() throws Exception {
if (isNullOrEmptyString(id)) {
Baotest = new Baotest();
} else {
Baotest = (Baotest)BaotestManager.getById(id);
}
}
/** 通过spring自动注入 */
public void setBaotestManager(BaotestManager manager) {
this.BaotestManager = manager;
}
public Object getModel() {
return Baotest;
}
public void setId(java.lang.Long val) {
this.id = val;
}
public void setItems(String[] items) {
this.items = items;
}
/**
* ExtGrid使用
* 列表
* @throws IOException
*/
public void extlist() throws IOException
{
PageRequest<Map> pr = ExtJsPageHelper.createPageRequestForExtJs(getRequest(), DEFAULT_SORT_COLUMNS);
Page page = BaotestManager.findByPageRequest(pr);
List<Baotest> Baotestlist = (List) page.getResult();
ListRange<Baotest> resultList = new ListRange<Baotest>();
resultList.setList(Baotestlist);
resultList.setTotalSize(page.getTotalCount());
resultList.setMessage("ok");
resultList.setSuccess(true);
outJson(resultList);
}
/**
* extGrid保存
* @throws IOException
*/
public void extsave() throws IOException
{
Map<String, Object> result = new HashMap<String, Object>();
try
{
BaotestManager.save(Baotest);
result.put("success", true);
result.put("msg", "添 加 成 功!");
}
catch (Exception e)
{
result.put("failure", true);
result.put("msg", e.getMessage());
e.printStackTrace();
}
outJson(result);
}
/**
* extGrid修改
* @throws IOException
*/
public void extupdate() throws IOException
{
Map<String, Object> result = new HashMap<String, Object>();
try
{
BaotestManager.update(Baotest);
result.put("success", true);
result.put("msg", "修 改 成 功!");
}
catch (Exception e)
{
result.put("failure", true);
result.put("msg", e.getMessage());
e.printStackTrace();
}
outJson(result);
}
/**
* extGrid删除
* @throws IOException
*/
public void extdelete() throws IOException
{
String ids = getRequest().getParameter("ids");
String[] idarray = ids.split(",");
Map<String, Object> result = new HashMap<String, Object>();
try
{
for (int i = 0; i < idarray.length; i++)
{
java.lang.Long id = new java.lang.Long((String)idarray[i]);
BaotestManager.removeById(id);
}
result.put("success", true);
result.put("msg", "删除成功");
}
catch (Exception e)
{
result.put("failure", true);
result.put("msg", e.getMessage());
e.printStackTrace();
}
outJson(result);
}
}
接下来写配置文件:
web.xml, 这里主要是加载 struts和spring配置。
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.4" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <!-- session超时定义,单位为分钟 --> <session-config> <session-timeout>10</session-timeout> </session-config> <!-- 默认首页定义 --> <welcome-file-list> <welcome-file>index.jsp</welcome-file> <welcome-file>index.html</welcome-file> </welcome-file-list> <!-- Error Page定义 --> <error-page> <error-code>500</error-code> <location>/commons/error.jsp</location> </error-page> <error-page> <error-code>404</error-code> <location>/commons/404.jsp</location> </error-page> <error-page> <error-code>403</error-code> <location>/commons/403.jsp</location> </error-page> <!-- Spring ApplicationContext配置文件的路径�,可使用通配符,多个路径用�1,号分隔 此参数用于后面的Spring-Context loader --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:spring/*.xml</param-value> </context-param> <!-- 默认i18n资源文件 --> <context-param> <param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name> <param-value>i18n/messages</param-value> </context-param> <!-- ExtremeTable 表格标签的Properties文件 --> <context-param> <param-name>extremecomponentsPreferencesLocation</param-name> <param-value>/extremetable.properties</param-value> </context-param> <context-param> <param-name>extremecomponentsMessagesLocation</param-name> <param-value>i18n/messages</param-value> </context-param> <!-- 著名 Character Encoding filter --> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <!-- ExtremeTable 导出Excel和Pdf的Filter --> <filter> <filter-name>eXtremeExport</filter-name> <filter-class>org.extremecomponents.table.filter.ExportFilter</filter-class> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter-mapping> <filter-name>eXtremeExport</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!--Spring ApplicationContext 载入 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 使Spring支持request与session的scope,如:<bean id="loginAction" class="com.foo.LoginAction" scope="request"/> --> <listener> <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class> </listener> <!-- Spring 刷新Introspector防止内存泄露 --> <listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener> <filter> <filter-name>struts2-cleanup</filter-name> <filter-class>org.apache.struts2.dispatcher.ActionContextCleanUp</filter-class> </filter> <filter> <filter-name>struts2Filter</filter-name> <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class> </filter> <filter-mapping> <filter-name>struts2-cleanup</filter-name> <url-pattern>*.do</url-pattern> </filter-mapping> <filter-mapping> <filter-name>struts2Filter</filter-name> <url-pattern>*.do</url-pattern> </filter-mapping> </web-app>
struts2 配置文件
<?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"> <!-- 修改说明: 1.修改pakcage的namespace属性,因为URL访问规则是: /namesapce/Entity/method.do 2.根据你的包结构修改action节点的class属性 --> <struts> <constant name="struts.devMode" value="true" /> <!-- struts的URL扩展名 --> <constant name="struts.action.extension" value="do" /> <!-- 允许访问静态成员变量 --> <constant name="struts.ognl.allowStaticMethodAccess" value="true" /> <constant name="struts.custom.i18n.resources" value="i18n/messages"/> <constant name="struts.enable.DynamicMethodInvocation" value="false" /> <constant name="struts.enable.SlashesInActionNames" value="true" /> <package name="custom-default" extends="struts-default"> <result-types> <result-type name="direct"
class="cn.org.rapid_framework.struts2.dispatcher.DirectResult"/> </result-types> <default-interceptor-ref name="paramsPrepareParamsStack"/> </package> <!-- 修改为你自己的namespace --> <package name="default" namespace="/" extends="custom-default"> <!-- 通过URL访问的路径是 /namesapce/Entity/method.do --> <action name="*/*" method="{2}"
class="com.mylink.mipbs.action.{1}Action"> <result name="*" type="direct">
通过Action直接返回,这一行无需修改</result> </action> <!-- 打开以下配置用于使用struts2自带的验证框架 <action name="*/save" method="save"
class="com.company.system.action.{1}Action"> <result name="input" type="dispatcher">
/demo/{1}/create.do</result> <result name="*" type="direct">通过Action直接返回</result> </action> <action name="*/update" method="update"
class="com.company.system.action.{1}Action"> <result name="input" type="dispatcher">
/demo/{1}/edit.do</result> <result name="*" type="direct">通过Action直接返回</result> </action> --> </package> </struts>
通配符使用, */* 第一个*,就是 {1} , 第二个* 就是{2}.如:/Baotest/query.do
<!-- 通过URL访问的路径是 /namesapce/Entity/method.do --> <action name="*/*" method="{2}" class="com.mylink.mipbs.action.{1}Action"> <result name="*" type="direct">通过Action直接返回,这一行无需修改</result> </action>
Spring配置:
1: applicationContext-service.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd"
default-autowire="byName" default-lazy-init="false">
<!-- component-scan自动搜索@Component ,
@Controller , @Service , @Repository等标注的类 -->
<!-- 默认值如果适合,该项可以不用修改 -->
<context:component-scan base-package="com.**.service.impl" />
</beans>
2: applicationContext-ibatis3-dao.xml
<?xml version="1.0" encoding="UTF-8"?>
<!--
-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/
schema/context/spring-context-3.0.xsd"
default-autowire="byName" default-lazy-init="false">
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- Transaction manager for a single JDBC DataSource -->
<bean id="transactionManager" class=
"org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="sqlSessionFactory" class="javacommon.SqlSessionFactoryFactoryBean">
<property name="configLocation" value="classpath:configuration.xml"/>
<property name="mapperLocations" value="classpath*:/com/**/model/**/*Mapper.xml"/>
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- component-scan自动搜索@Component , @Controller , @Service , @Repository等标注的类 -->
<context:component-scan base-package="com.**.dao"/>
</beans>
待续...