您的位置:首页 > 编程语言 > Java开发

Struts2、Spring3、MyBatis3整合ExtJS,完成ColumnTree 【二】

2011-05-11 17:38 627 查看

三、加入Struts2框架

1、准备工作添加jar文件如下:

org.springframework.web-3.0.5.RELEASE.jarorg.springframework.aop-3.0.5.RELEASE.jar这2个jar包是spring的context所依赖的jar包struts2-spring-plugin-2.2.3.jar是struts整合spring的jar包2、在web.xml加入struts2的控制器
[code]<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>
[/code]
3、在src目录添加struts.xml
[code]<?xmlversion="1.0"encoding="UTF-8"?>
<!DOCTYPEstrutsPUBLIC
"-//ApacheSoftwareFoundation//DTDStrutsConfiguration2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constantname="struts.i18n.encoding"value="UTF-8"/>
<packagename="ssMyBatis"extends="struts-default">
</package>
</struts>
[/code]
启动后,可以看到首页index的页面就基本整合完成。
4、首先看看Action代码,代码如下:
[code]packagecom.hoo.action;
importjava.util.ArrayList;
importjava.util.List;
importjavax.inject.Inject;
importjavax.inject.Named;
importorg.springframework.stereotype.Component;
importcom.hoo.biz.AccountBiz;
importcom.hoo.entity.Account;
importcom.opensymphony.xwork2.ActionSupport;
/**
*<b>function:</b>AccountAction
*@authorhoojo
*@createDate2011-5-11下午12:03:05
*@fileAccountAction.java
*@packagecom.hoo.action
*@projectS2SMyBatis
*@blog
'target='_blank'>http://blog.csdn.net/IBM_hoojo
*@emailhoojo_@126.com
*@version1.0
*/
@Component
publicclassAccountActionextendsActionSupport{
/**
*@authorHoojo
*/
privatestaticfinallongserialVersionUID=-973535478139284399L;
@Inject
@Named("accountBiz")
privateAccountBiz<Account>biz;
privateAccountacc;
privateList<Account>results=newArrayList<Account>();
publicList<Account>getResults(){
returnresults;
}
publicAccountgetAcc(){
returnacc;
}
publicvoidsetAcc(Accountacc){
this.acc=acc;
}
publicStringadd()throwsException{
if(!biz.addAccount(acc)){
this.addActionMessage("添加数据失败");
returnERROR;
}
returnSUCCESS;
}
publicStringshow()throwsException{
results=biz.getList();
return"show";
}
publicStringremove()throwsException{
returnSUCCESS;
}
publicStringedit()throwsException{
returnSUCCESS;
}
publicStringtreeData()throwsException{
results=biz.getList();
return"tree";
}
}
[/code]
这个Action被注解成Component,那么在spring的applicationContext配置文件中就不需要进行<bean/>标签的配置了。上面注入了AccountDao,完成相关操作。
5、由于Struts2要和Spring进行整合,所以struts的配置会有点不同

[code]<actionname="account"class="accountAction">
<resulttype="redirect">account!show.action</result>
<resultname="show">/show.jsp</result>
</action>
[/code]
上面的class不再是AccountAction的classpath,而是spring容器中配置的bean。就是通过@Component注解过的AccountAction,被注解注释过后它的id默认是类名称首字母小写。所以上面的action的配置是accountAction。
6、由于要整合ExtJS,所以这里用到struts2-json-plugin-2.2.3.jar这个插件,将其加入到lib库中,struts.xml更改成:
[code]<?xmlversion="1.0"encoding="UTF-8"?>
<!DOCTYPEstrutsPUBLIC
"-//ApacheSoftwareFoundation//DTDStrutsConfiguration2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constantname="struts.i18n.encoding"value="UTF-8"/>
<packagename="ssMyBatis"extends="json-default">
<global-results>
<resultname="error">/error.jsp</result>
</global-results>
<actionname="account"class="accountAction">
<resulttype="redirect">account!show.action</result>
<resultname="show">/show.jsp</result>
<resultname="tree"type="json">
<paramname="excludeProperties">acc</param>
</result>
</action>
</package>
</struts>
[/code]
AccountAction中的treeData方法返回的tree,在account这个action配置中找到tree的result,将result的type配置成json。表示该result的数据以json的方式展示。tree这个result还配置了一个param,名称为excludeProperties表示排除的属性。这个参数将排除当前Action中的acc属性。也就是说这个属性将不会得到json的转换。其他属性将会被转换成json。
7、前台页面
index.jsp
[code]<body>
<ahref="account!show.action">显示所有</a><br>
<ahref="add.jsp">添加数据</a><br/>
<ahref="account!treeData.action">JSON</a><br/>
</body>
[/code]
show.jsp

[code]<%@pagelanguage="java"import="java.util.*"pageEncoding="UTF-8"%>
<%@taglibprefix="s"uri="/struts-tags"%>
<%
Stringpath=request.getContextPath();
StringbasePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN">
<html>
<head>
<basehref="<%=basePath%>">
<title>showalldata</title>
<metahttp-equiv="pragma"content="no-cache">
<metahttp-equiv="cache-control"content="no-cache">
<metahttp-equiv="expires"content="0">
</head>
<body>
<s:iteratorvalue="results"status="s"var="data">
${data}<===>
<s:propertyvalue="#data.accountId"/>#
<s:propertyvalue="#data.username"/>#
<s:propertyvalue="#data.password"/>#
<s:propertyvalue="#data.createTime"/>#
<s:datename="#data.createTime"format="yyyy-MM-dd"/>#
<ahref="account!remove.action">删除</a>|<ahref="account!edit.action">修改</a>
<br/>
</s:iterator>
</body>
</html>
[/code]
Struts标签和OGNL表达式显示数据
add.jsp

[code]<%@pagelanguage="java"import="java.util.*"pageEncoding="UTF-8"%>
<%@taglibprefix="s"uri="/struts-tags"%>
<%
Stringpath=request.getContextPath();
StringbasePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN">
<html>
<head>
<basehref="<%=basePath%>">
<title>add</title>
<metahttp-equiv="pragma"content="no-cache">
<metahttp-equiv="cache-control"content="no-cache">
<metahttp-equiv="expires"content="0">
</head>
<body>
<s:formaction="account!add.action"method="post">
<s:textfieldname="acc.username"/>
<s:passwordname="acc.password"/>
<s:submitvalue="提交"></s:submit>
</s:form>
</body>
</html>
[/code]

四、整合ExtJS

1、添加ext的库,版本是2.2.2
需要添加column-tree.css
[code]/*
*ExtJSLibrary2.2.1
*Copyright(c)2006-2009,ExtJS,LLC.
*licensing@extjs.com
*
*
'target='_blank'>http://extjs.com/license
*/
.x-column-tree.x-tree-node{
zoom:1;
}
.x-column-tree.x-tree-node-el{
/*border-bottom:1pxsolid#eee;borders?*/
zoom:1;
}
.x-column-tree.x-tree-selected{
background:#d9e8fb;
}
.x-column-tree.x-tree-nodea{
line-height:18px;
vertical-align:middle;
}
.x-column-tree.x-tree-nodeaspan{
}
.x-column-tree.x-tree-node.x-tree-selectedaspan{
background:transparent;
color:#000;
}
.x-tree-col{
float:left;
overflow:hidden;
padding:01px;
zoom:1;
}
.x-tree-col-text,.x-tree-hd-text{
overflow:hidden;
-o-text-overflow:ellipsis;
text-overflow:ellipsis;
padding:3px3px3px5px;
white-space:nowrap;
font:normal11pxarial,tahoma,helvetica,sans-serif;
}
.x-tree-headers{
background:#f9f9f9url(../ext2/resources/images/default/grid/grid3-hrow.gif)repeat-x0bottom;
cursor:default;
zoom:1;
}
.x-tree-hd{
float:left;
overflow:hidden;
border-left:1pxsolid#eee;
border-right:1pxsolid#d0d0d0;
}
.task{
background-image:url(../shared/icons/fam/cog.png)!important;
}
.task-folder{
background-image:url(../shared/icons/fam/folder_go.png)!important;
}
[/code]
Ext.tree.ColumnTree.js
[code]/*
*ExtJSLibrary2.2.1
*Copyright(c)2006-2009,ExtJS,LLC.
*licensing@extjs.com
*
*
'target='_blank'>http://extjs.com/license
*/
Ext.tree.ColumnTree=Ext.extend(Ext.tree.TreePanel,{
lines:false,
borderWidth:Ext.isBorderBox?0:2,//thecombinedleft/rightborderforeachcell
cls:'x-column-tree',
onRender:function(){
Ext.tree.ColumnTree.superclass.onRender.apply(this,arguments);
this.headers=this.body.createChild(
{cls:'x-tree-headers'},this.innerCt.dom);
varcols=this.columns,c;
vartotalWidth=0;
for(vari=0,len=cols.length;i<len;i++){
c=cols[i];
totalWidth+=c.width;
this.headers.createChild({
cls:'x-tree-hd'+(c.cls?c.cls+'-hd':''),
cn:{
cls:'x-tree-hd-text',
html:c.header
},
style:'width:'+(c.width-this.borderWidth)+'px;'
});
}
this.headers.createChild({cls:'x-clear'});
//preventfloatsfromwrappingwhenclipped
this.headers.setWidth(totalWidth);
this.innerCt.setWidth(totalWidth);
}
});
Ext.tree.ColumnNodeUI=Ext.extend(Ext.tree.TreeNodeUI,{
focus:Ext.emptyFn,//preventoddscrollingbehavior
renderElements:function(n,a,targetNode,bulkRender){
this.indentMarkup=n.parentNode?n.parentNode.ui.getChildIndent():'';
vart=n.getOwnerTree();
varcols=t.columns;
varbw=t.borderWidth;
varc=cols[0];
varbuf=[
'<liclass="x-tree-node"><divext:tree-node-id="',n.id,'"class="x-tree-node-elx-tree-node-leaf',a.cls,'">',
'<divclass="x-tree-col"style="width:',c.width-bw,'px;">',
'<spanclass="x-tree-node-indent">',this.indentMarkup,"</span>",
'<imgsrc="',this.emptyIcon,'"class="x-tree-ec-iconx-tree-elbow">',
'<imgsrc="',a.icon||this.emptyIcon,'"class="x-tree-node-icon',(a.icon?"x-tree-node-inline-icon":""),(a.iconCls?""+a.iconCls:""),'"unselectable="on">',
'<ahidefocus="on"class="x-tree-node-anchor"href="',a.href?a.href:"#",'"tabIndex="1"',
a.hrefTarget?'target="'+a.hrefTarget+'"':"",'>',
'<spanunselectable="on">',n.text||(c.renderer?c.renderer(a[c.dataIndex],n,a):a[c.dataIndex]),"</span></a>",
"</div>"];
for(vari=1,len=cols.length;i<len;i++){
c=cols[i];
buf.push('<divclass="x-tree-col',(c.cls?c.cls:''),'"style="width:',c.width-bw,'px;">',
'<divclass="x-tree-col-text">',(c.renderer?c.renderer(a[c.dataIndex],n,a):a[c.dataIndex]),"</div>",
"</div>");
}
buf.push(
'<divclass="x-clear"></div></div>',
'<ulclass="x-tree-node-ct"style="display:none;"></ul>',
"</li>");
if(bulkRender!==true&&n.nextSibling&&n.nextSibling.ui.getEl()){
this.wrap=Ext.DomHelper.insertHtml("beforeBegin",
n.nextSibling.ui.getEl(),buf.join(""));
}else{
this.wrap=Ext.DomHelper.insertHtml("beforeEnd",targetNode,buf.join(""));
}
this.elNode=this.wrap.childNodes[0];
this.ctNode=this.wrap.childNodes[1];
varcs=this.elNode.firstChild.childNodes;
this.indentNode=cs[0];
this.ecNode=cs[1];
this.iconNode=cs[2];
this.anchor=cs[3];
this.textNode=cs[3].firstChild;
}
});
[/code]
2、编写静态ColumnTree
[code]/**
*@functioncolumntreecolumntree多列信息的tree
*@auhor:hoojo
*@createDate:Aug29,201010:39:02PM
*@blog:blog.csdn.net/IBM_hoojo
*@email:hoojo_@126.com
*/
Ext.ns("Ext.hoo.tree");
Ext.hoo.tree.UserColumnTree=Ext.extend(Ext.tree.ColumnTree,{
constructor:function(){
Ext.hoo.tree.UserColumnTree.superclass.constructor.call(this,{
renderTo:"show",
title:"用户信息columntree",
width:450,
hieght:400,
autoScroll:true,
rootVisible:true,
columns:[{
header:"名称",
width:100,
dataIndex:"name"
},{
header:"性别",
width:100,
dataIndex:"sex"
},{
header:"年龄",
width:100,
dataIndex:"age"
},{
header:"班级",
width:100,
dataIndex:"classes"
}],
loader:newExt.tree.TreeLoader({
baseAttrs:{
uiProvider:Ext.tree.ColumnNodeUI
}
}),
root:newExt.tree.AsyncTreeNode({
text:"用户基本信息",
children:[{
name:"大二一班",
classes:"二(1)班",
children:[{
name:"微微",
sex:"女",
age:20,
classes:"二(1)班",
leaf:true
},{
name:"筱筱",
sex:"女",
age:22,
classes:"二(1)班",
leaf:true
},{
name:"珠珠",
sex:"女",
age:19,
classes:"二(1)班",
leaf:true
},{
name:"拉拉",
sex:"女",
age:19,
classes:"二(1)班",
leaf:true
}]
},{
name:"二二班",
classes:"二(2)班",
children:[{
name:"放放",
sex:"男",
age:22,
classes:"二(2)班",
leaf:true
},{
name:"枫枫",
sex:"男",
age:22,
classes:"二(2)班",
leaf:true
}]
},{
name:"未成立",
sex:"",
age:0,
classes:"二(3)班",
leaf:true
}]
})
});
this.on("click",this.onNodeClick,this);
},
onNodeClick:function(node,e){
alert(Ext.encode(node.attributes)+"###"+node.leaf+"###"+Ext.encode(e.getPoint())+"##"+e.getXY());
}
});
Ext.onReady(function(){
Ext.BLANK_IMAGE_URL="ext2/resources/images/default/s.gif";
newExt.hoo.tree.UserColumnTree();
});
[/code]
上面的就是一个静态的ColumnTree,在Ext的onReady函数中运行它。
3、、需要在页面中导入ext库、css、即我们编写的js

[code]<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>TreePanel示例</title>
<metahttp-equiv="Content-Type"content="text/html;charset=UTF-8"/>
<metahttp-equiv="author"content="hoojo"/>
<metahttp-equiv="email"content="hoojo_@126.com"/>
<metahttp-equiv="ext-lib"content="version2.2"/>
<metahttp-equiv="blog"content="http://blog.csdn.net/IBM_hoojo"/>
<metahttp-equiv="blog"content="http://hoojo.cnblogs.com"/>
<linkrel="stylesheet"type="text/css"href="ext2/resources/css/ext-all.css"/>
<linkrel="stylesheet"type="text/css"href="jslib/column-tree.css"/>
<scripttype="text/javascript"src="ext2/adapter/ext/ext-base.js"></script>
<scripttype="text/javascript"src="ext2/ext-all.js"></script>
<scripttype="text/javascript"src="ext2/build/locale/ext-lang-zh_CN-min.js"></script>
<scripttype="text/javascript"src="jslib/Ext.tree.ColumnTree.js"></script>
<scripttype="text/javascript"src="jslib/Ext.hoo.tree.UserColumnTree.js"></script>
</head>
<body>
<divid="show"style="margin-left:200px;"></div>
<divid="showBasic"style="margin-left:200px;margin-top:50px;"></div>
</body>
</html>
[/code]
在浏览器中请求http://localhost:8080/S2SMyBatis/columnTree.htm
结果如下



4、下面编写远程数据的ColumnTree,代码如下:
[code]Ext.ns("Ext.hoo.tree");
Ext.hoo.tree.UserBasicColumnTree=Ext.extend(Ext.tree.ColumnTree,{
constructor:function(){
Ext.hoo.tree.UserBasicColumnTree.superclass.constructor.call(this,{
renderTo:"showBasic",
title:"远程数据",
width:550,
hieght:400,
autoScroll:true,
rootVisible:true,
columns:[{
header:"编号",
width:100,
dataIndex:"accountId"
},{
header:"用户名称",
width:100,
dataIndex:"username"
},{
header:"密码",
width:100,
dataIndex:"password"
},{
header:"创建时间",
width:150,
dataIndex:"createTime"
}],
loader:newExt.tree.TreeLoader({
baseAttrs:{
uiProvider:Ext.tree.ColumnNodeUI
}
}),
root:newExt.tree.AsyncTreeNode({
text:"用户基本信息",
children:[]
}),
listeners:{
expandnode:{
fn:this.onExpandNode,
scope:this
}
}
});
},
onExpandNode:function(node){
//只对未加载过的添加子结点,加载后不在重复加载;避免增加请求,浪费资源
if(!node.attributes.isLoad){
Ext.Ajax.request({
url:Ext.hoo.tree.UserBasicColumnTree.TREE_DATA_URL,
success:function(response,options){
node.attributes.isLoad=true;//设置加载标识
varnodes=Ext.decode(response.responseText);//将json的text转换成js对象
node.appendChild(nodes.results);
},
failure:function(response){
Ext.Msg.alert("程序异常",response.responseText);
}
});
}
}
});
Ext.hoo.tree.UserBasicColumnTree.TREE_DATA_URL="account!treeData.action";
[/code]
由于服务器端返回来的数据是一个对象,而不是一个Array。所以客户端要将数据稍作处理,然后再添加到columnTree的children中。
5、在上面的onReady中创建这个对象就可以了运行

[code]Ext.onReady(function(){
Ext.BLANK_IMAGE_URL="ext2/resources/images/default/s.gif";
newExt.hoo.tree.UserColumnTree();
newExt.hoo.tree.UserBasicColumnTree();
});
[/code]
同样在浏览器中请求http://localhost:8080/S2SMyBatis/columnTree.htm
可以看到



由于Account对象的数据形式不是一个完整的tree形态。所以展示效果就是上面的样子。正确的数据的格式的话,Account中至少包含以下属性:
Booleanleaf;Listchildren;这样就知道当前节点是否是叶子节点,并且知道其子元素。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: