摘要: 之前項(xiàng)目有個(gè)模塊要求用樹(shù)形解決,附帶要實(shí)現(xiàn)checkbox,增刪修改以及copy/cut/paste等等功能;
因?yàn)橹皩?xiě)的人用了xloadTree,其他功能都實(shí)現(xiàn)了,但是客戶(hù)要求要有cookie功能,實(shí)現(xiàn)不了麻煩啊~
正巧現(xiàn)在在學(xué)習(xí)用Ext,發(fā)現(xiàn)Ext的tree本身就很強(qiáng)大基本的功能都可以實(shí)現(xiàn)。
Code highlighting produced by Actipro Cod... 閱讀全文
2009年10月20日 #
Border布局作為Ext中整個(gè)框架的布局應(yīng)該說(shuō)很普遍,一般North放一個(gè)應(yīng)用的Logo bar,West一般會(huì)作為導(dǎo)航欄的放置位置;
而Center(East)往往作為整個(gè)應(yīng)用的核心部分,而South位置也往往放置一些應(yīng)用的版權(quán)等信息。
而導(dǎo)航欄一般會(huì)采用的呈現(xiàn)方式一般無(wú)非是Treepanel或者根據(jù)模塊放置多個(gè)Panel,而多數(shù)會(huì)采用的布局方式,往往是
Accordion的布局。比如像這樣(偷個(gè)懶直接用設(shè)計(jì)器寫(xiě)的):
而IE呢,在第一次導(dǎo)航欄寬帶變大的時(shí)候,一切正常;而當(dāng)導(dǎo)航欄寬度縮小的時(shí)候,原來(lái)每行的按鍵數(shù)卻并不變。想想這Ext都3.2了,不會(huì)還有這么腦殘的bug吧;
google了下,國(guó)內(nèi)似乎對(duì)這個(gè)問(wèn)題也沒(méi)有什么討論的;于是直接去官網(wǎng)的論壇問(wèn)。
最初別人的提議是,更改westPanel的屬性

因?yàn)槊看沃挥?個(gè)子欄目的寬度在變化,所以產(chǎn)生這個(gè)問(wèn)題也不足為奇了。
最后某個(gè)網(wǎng)友提供了一個(gè)自己寫(xiě)的補(bǔ)丁,問(wèn)題解決了。
而Center(East)往往作為整個(gè)應(yīng)用的核心部分,而South位置也往往放置一些應(yīng)用的版權(quán)等信息。
而導(dǎo)航欄一般會(huì)采用的呈現(xiàn)方式一般無(wú)非是Treepanel或者根據(jù)模塊放置多個(gè)Panel,而多數(shù)會(huì)采用的布局方式,往往是
Accordion的布局。比如像這樣(偷個(gè)懶直接用設(shè)計(jì)器寫(xiě)的):
MyViewportUi = Ext.extend(Ext.Viewport, {
layout: 'border',
initComponent: function() {
this.items = [
{
xtype: 'panel',
title: 'north',
region: 'north'
},
{
xtype: 'panel',
title: 'west',
region: 'west',
width: 201,
split: true,
layout: 'accordion',
activeItem: 0,
items: [
{
xtype: 'panel',
title: 'panel1',
layout: 'column',
width: 180,
items: [
{
xtype: 'button',
text: 'Button1',
scale: 'large'
},
{
xtype: 'button',
text: 'Button2',
scale: 'large'
},
{
xtype: 'button',
text: 'Button3',
scale: 'large'
},
{
xtype: 'button',
text: 'Button4',
scale: 'large'
},
{
xtype: 'button',
text: 'Button5',
scale: 'large'
},
{
xtype: 'button',
text: 'Button6',
scale: 'large'
}
]
},
{
xtype: 'panel',
title: 'panel2'
},
{
xtype: 'panel',
title: 'panel3'
}
]
},
{
xtype: 'panel',
title: 'east',
region: 'center'
},
{
xtype: 'panel',
title: 'south',
region: 'south'
}
];
MyViewportUi.superclass.initComponent.call(this);
}
});
一個(gè)基本的框架就產(chǎn)生了,而問(wèn)題也隨之而來(lái)。最主要的問(wèn)題是IE和FF顯示不一樣。應(yīng)該說(shuō)FF顯示很正常,按鍵根據(jù)導(dǎo)航欄的大小,改變每一行顯示的數(shù)量;layout: 'border',
initComponent: function() {
this.items = [
{
xtype: 'panel',
title: 'north',
region: 'north'
},
{
xtype: 'panel',
title: 'west',
region: 'west',
width: 201,
split: true,
layout: 'accordion',
activeItem: 0,
items: [
{
xtype: 'panel',
title: 'panel1',
layout: 'column',
width: 180,
items: [
{
xtype: 'button',
text: 'Button1',
scale: 'large'
},
{
xtype: 'button',
text: 'Button2',
scale: 'large'
},
{
xtype: 'button',
text: 'Button3',
scale: 'large'
},
{
xtype: 'button',
text: 'Button4',
scale: 'large'
},
{
xtype: 'button',
text: 'Button5',
scale: 'large'
},
{
xtype: 'button',
text: 'Button6',
scale: 'large'
}
]
},
{
xtype: 'panel',
title: 'panel2'
},
{
xtype: 'panel',
title: 'panel3'
}
]
},
{
xtype: 'panel',
title: 'east',
region: 'center'
},
{
xtype: 'panel',
title: 'south',
region: 'south'
}
];
MyViewportUi.superclass.initComponent.call(this);
}
});
而IE呢,在第一次導(dǎo)航欄寬帶變大的時(shí)候,一切正常;而當(dāng)導(dǎo)航欄寬度縮小的時(shí)候,原來(lái)每行的按鍵數(shù)卻并不變。想想這Ext都3.2了,不會(huì)還有這么腦殘的bug吧;
google了下,國(guó)內(nèi)似乎對(duì)這個(gè)問(wèn)題也沒(méi)有什么討論的;于是直接去官網(wǎng)的論壇問(wèn)。
最初別人的提議是,更改westPanel的屬性
layout: {
type: 'accordion',
autoWidth: false
}
等于禁止westPanel的子欄目自動(dòng)變化寬度,試了如果westPanel的子欄目只有一個(gè)工作正常,但是如果多個(gè)的話(huà),又悲劇了~type: 'accordion',
autoWidth: false
}
因?yàn)槊看沃挥?個(gè)子欄目的寬度在變化,所以產(chǎn)生這個(gè)問(wèn)題也不足為奇了。
最后某個(gè)網(wǎng)友提供了一個(gè)自己寫(xiě)的補(bǔ)丁,問(wèn)題解決了。
Ext.layout.AccordionPatch = Ext.extend(Ext.layout.Accordion, {
inactiveItems: [],//ADDED
// private
onLayout : function(ct, target){//ADDED
Ext.layout.AccordionPatch.superclass.onLayout.call(this, ct, target);
if(this.autoWidth === false) {
for(var i = 0; i < this.inactiveItems.length; i++) {
var item = this.inactiveItems[i];
item.setSize(target.getStyleSize());
}
}
},
// private
beforeExpand : function(p, anim){//MODFIED
var ai = this.activeItem;
if(ai){
if(this.sequence){
delete this.activeItem;
ai.collapse({callback:function(){
p.expand(anim || true);
}, scope: this});
return false;
}else{
ai.collapse(this.animate);
if(this.autoWidth === false && this.inactiveItems.indexOf(ai) == -1)//*****
this.inactiveItems.push(ai);//*****
}
}
this.activeItem = p;
if(this.activeOnTop){
p.el.dom.parentNode.insertBefore(p.el.dom, p.el.dom.parentNode.firstChild);
}
if(this.autoWidth === false && this.inactiveItems.indexOf(this.activeItem) != -1)//*****
this.inactiveItems.remove(this.activeItem);//*****
this.layout();
}
});
Ext.Container.LAYOUTS['accordionpatch'] = Ext.layout.AccordionPatch;
配合補(bǔ)丁,westPanel的屬性也要有相應(yīng)的變化inactiveItems: [],//ADDED
// private
onLayout : function(ct, target){//ADDED
Ext.layout.AccordionPatch.superclass.onLayout.call(this, ct, target);
if(this.autoWidth === false) {
for(var i = 0; i < this.inactiveItems.length; i++) {
var item = this.inactiveItems[i];
item.setSize(target.getStyleSize());
}
}
},
// private
beforeExpand : function(p, anim){//MODFIED
var ai = this.activeItem;
if(ai){
if(this.sequence){
delete this.activeItem;
ai.collapse({callback:function(){
p.expand(anim || true);
}, scope: this});
return false;
}else{
ai.collapse(this.animate);
if(this.autoWidth === false && this.inactiveItems.indexOf(ai) == -1)//*****
this.inactiveItems.push(ai);//*****
}
}
this.activeItem = p;
if(this.activeOnTop){
p.el.dom.parentNode.insertBefore(p.el.dom, p.el.dom.parentNode.firstChild);
}
if(this.autoWidth === false && this.inactiveItems.indexOf(this.activeItem) != -1)//*****
this.inactiveItems.remove(this.activeItem);//*****
this.layout();
}
});
Ext.Container.LAYOUTS['accordionpatch'] = Ext.layout.AccordionPatch;
layout: {
type: 'accordionpatch',
autoWidth: false
}
type: 'accordionpatch',
autoWidth: false
}
摘要: 發(fā)表,瀏覽,回復(fù)之后,我們將討論的是刪除和編輯留言。
因?yàn)檫@個(gè)只是一個(gè)簡(jiǎn)單的留言板,沒(méi)有用戶(hù)認(rèn)證之類(lèi)繁瑣的事情,所以對(duì)于編輯和刪除留言,必須輸入
正確的id號(hào)和password;如果在發(fā)表或回復(fù)留言的時(shí)候沒(méi)有輸入密碼的話(huà),就不能對(duì)留言進(jìn)行編輯或者刪除。
這里將寫(xiě)的EditAction class與之前的有所不同,extends org.apache.struts.actions.Dispat... 閱讀全文
整個(gè)項(xiàng)目第二個(gè)重點(diǎn)就是回復(fù)留言,我的思路是在瀏覽留言的時(shí)候,回復(fù)鍵傳送主題的ID,一個(gè)Action Class處理這個(gè)請(qǐng)求,
將與這個(gè)ID相關(guān)的留言查詢(xún)出來(lái),寫(xiě)入ActionForm。
將與這個(gè)ID相關(guān)的留言查詢(xún)出來(lái),寫(xiě)入ActionForm。
- 打開(kāi)display.jsp文件,找到下面這幾行,后面添加一個(gè)form,用來(lái)提交查詢(xún)請(qǐng)求。
1 <table>6-11行,就是新加入的對(duì)id的一個(gè)請(qǐng)求,這里我用了普通的html標(biāo)志來(lái)提交請(qǐng)求,當(dāng)然我們也可以用<html:hidden name="topic" property="post.id"/>,但是在處理請(qǐng)求的時(shí)候,相對(duì)的request.getParameter("id"),就要換成
2 <tr>
3 <td>
4 <bean:write name="topic" property="post.subject"/> 留言者:<bean:write name="topic" property="post.name" /> 留言日:<bean:write name="topic" property="post.date" format="yyyy/MM/dd(E) HH:mm" /> No.<bean:write name="topic" property="post.id" />
5 </td>
6 <td>
7 <html:form action="read">
8 <input type="hidden" name="id" value="<bean:write name='topic' property='post.id'/>"/>
9 <html:submit value="回復(fù)" />
10 </html:form>
11 </td>
12 </tr>
13 </table>
request.getParameter("post.id")了;或者我們可以在那個(gè)Topic類(lèi)里,添加一個(gè)id字段,那么在瀏覽留言的時(shí)候(ListAction的execute方法,list.add(new Topic(post,replies)); 改成list.add(new Topic(post,replies,post.getId()));)<html:hidden name="topic" property="id"/>也可以這樣用了。
- 添加一個(gè)ActionForm bean ThreadForm.java,除了記錄一段留言外,還包括了行將用以回復(fù)的留言的預(yù)處理;
1 public class ThreadForm extends org.apache.struts.action.ActionForm {3-15行是負(fù)責(zé)對(duì)回復(fù)的預(yù)處理,ThreadForm()方法中主要也是處理圖標(biāo)。
2
3 private int id;
4 private String name;
5 private String subject;
6 private String content;
7 private String url;
8 private String email;
9 private int iconId;
10 private String icon;
11 private String password;
12 private int replyId;
13 private String font;
14
15 private List icons;
16
17 private Topic topic;
18
19 // accessor methods..
20
21
22 public ThreadForm() {
23 super();
24 // TODO Auto-generated constructor stub
25 setUrl("http://");
26 setFont("#800000");
27 String sql = "select id,name,src from icon order by id";
28 QueryRunner qr = DbHelper.getQueryRunner();
29 List list = null;
30 try {
31 list = (List) qr.query(sql, new BeanListHandler(Icon.class));
32 // TODO Auto-generated constructor stub
33 } catch (SQLException ex) {
34 Logger.getLogger(ThreadForm.class.getName()).log(Level.SEVERE, null, ex);
35 }
36 setIcons(list);
37 }
38
39
40 }
41
- 這個(gè)回復(fù)過(guò)程其實(shí)是2部,1.預(yù)處理:包括列出與ID相關(guān)的留言,預(yù)設(shè)回復(fù)的默認(rèn)標(biāo)題以及對(duì)應(yīng)的回復(fù)id (replyId);2.回復(fù)留言,添加記錄。
a. PreReplyAction.java
public class PreReplyAction extends org.apache.struts.action.Action {
/* forward name="success" path="" */
private static final String SUCCESS = "bbs.read";
/**
* This is the action called from the Struts framework.
* @param mapping The ActionMapping used to select this instance.
* @param form The optional ActionForm bean for this request.
* @param request The HTTP Request we are processing.
* @param response The HTTP Response we are processing.
* @throws java.lang.Exception
* @return
*/
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
{
ThreadForm f = (ThreadForm) form;
String id = (String) request.getParameter("id");
String sql;
QueryRunner qr = DbHelper.getQueryRunner();
List list = null;
sql = "select * from guestbook where id = " + id;
try {
list = (List) qr.query(sql, new BeanListHandler(Post.class));
} catch (SQLException ex) {
Logger.getLogger(PreReplyAction.class.getName()).log(Level.SEVERE, null, ex);
}
Post post = null;
post = (Post)list.get(0);
List replies = null;
sql = "select * from guestbook where replyId =" + id + " order by id";
try {
replies = (List) qr.query(sql, new BeanListHandler(Post.class));
} catch (SQLException ex) {
Logger.getLogger(PreReplyAction.class.getName()).log(Level.SEVERE, null, ex);
}
Topic topic = new Topic(post,replies);
f.setTopic(topic);
f.setSubject("Re :" + post.getSubject());
f.setReplyId(post.getId());
return mapping.findForward(SUCCESS);
}
}
b. ReplyAction.java
1 public class ReplyAction extends org.apache.struts.action.Action {這個(gè)基本和添加留言的一直,只是在insert回復(fù)記錄以后,更新主題留言的最近的回復(fù)時(shí)間,可以保證瀏覽留言的時(shí)候,該主題能在最前端。
2
3 /* forward name="success" path="" */
4 private static final String SUCCESS = "bbs.reply";
5
6 /**
7 * This is the action called from the Struts framework.
8 * @param mapping The ActionMapping used to select this instance.
9 * @param form The optional ActionForm bean for this request.
10 * @param request The HTTP Request we are processing.
11 * @param response The HTTP Response we are processing.
12 * @throws java.lang.Exception
13 * @return
14 */
15 @Override
16 public ActionForward execute(ActionMapping mapping, ActionForm form,
17 HttpServletRequest request, HttpServletResponse response)
18 throws Exception {
19 ThreadForm f = (ThreadForm)form;
20 String sql = "insert into guestbook (name,subject,email,url,content,iconId,password,font,replyId,date,lastReplyTime) " +
21 "values(?,?,?,?,?,?,?,?,?,now(),now())";
22 String content = f.getContent();
23 content = content.replaceAll(" ", " ");
24 content = content.replaceAll("\n","<br>");
25 String params[] = {f.getName(),f.getSubject(),f.getEmail(),f.getUrl(),content,new Integer(f.getIconId()).toString(),f.getPassword(),f.getFont(),new Integer(f.getReplyId()).toString()};
26
27 QueryRunner qr = DbHelper.getQueryRunner();
28 try {
29 qr.update(sql, params);
30 } catch (SQLException ex) {
31 Logger.getLogger(ReplyAction.class.getName()).log(Level.SEVERE, null, ex);
32 }
33 sql = "update guestbook set lastReplyTime= now() where id = " + f.getReplyId();
34 try {
35 qr.update(sql);
36 } catch (SQLException ex) {
37 Logger.getLogger(ReplyAction.class.getName()).log(Level.SEVERE, null, ex);
38 }
39 return mapping.findForward(SUCCESS);
40 }
41 }
- reply.jsp 基本和之前寫(xiě)的jsp頁(yè)面區(qū)別不大,省略了。
- 添加相應(yīng)的forwarding信息。
<global-forwards>根據(jù)forward的指向,我們可以看到在reply.jsp按下回復(fù)鍵以后,直接轉(zhuǎn)向list.do動(dòng)作。
<forward name="bbs.post" path="/result.jsp"/>
<forward name="bbs.list" path="/display.jsp"/>
<forward name="bbs.read" path="/reply.jsp" />
<forward name="bbs.reply" path="/list.do" />
<forward name="welcome" path="/Welcome.do"/>
</global-forwards>
至于action-mapping 沒(méi)有什么要注意的。
- 整個(gè)回復(fù)過(guò)程就此完成。
摘要: 既然我們已經(jīng)成功完成了第一個(gè)ActionForm Bean和與之相關(guān)的Action Class;后面的專(zhuān)題中將不再詳細(xì)的去寫(xiě)與他們相關(guān)的開(kāi)發(fā)步驟了。
現(xiàn)在我們開(kāi)始寫(xiě)留言板的主體部分,即對(duì)整個(gè)留言就行瀏覽。因?yàn)槊總€(gè)post都有一個(gè)replyId字段,用來(lái)對(duì)應(yīng)其所回復(fù)的留言id;如果這個(gè)
replyId等于-1的話(huà),即該留言沒(méi)有對(duì)應(yīng)的回復(fù)。好了還是先從這個(gè)JSP頁(yè)面寫(xiě)起。
displ... 閱讀全文
PostAction主要是處理留言添加工作。
- 和創(chuàng)建NewForm bean一樣,點(diǎn)擊Source Packages > com.bbs.struts,右鍵New > Java Package... 創(chuàng)建一個(gè)com.bbs.struts.action的package用于存放所有action類(lèi);
- 右鍵com.bbs.struts.action, New > Struts Action...如果New菜單里沒(méi)有的話(huà),選擇other...,categories里選擇
Struts,F(xiàn)ile types一欄里選擇Struts Action ...;
- 在New Struts Action面板里面,Class Name填PostAction;Action Path 填/post;按Next
- 按照下面的設(shè)置,完成對(duì)Action的設(shè)置
- 在struts-config.xml的文檔中,IDE自動(dòng)添加了對(duì)PostForm的聲明。
<action-mappings>
<action input="/post.jsp" name="NewForm" path="/post" scope="request" type="com.bbs.struts.action.PostAction"/>
<action path="/Welcome" forward="/welcomeStruts.jsp"/>
</action-mappings>
- 右邊的Source Editor中,新建的PostAction.java已經(jīng)打開(kāi)了;接下來(lái)我們要把記錄在NewForm bean里的數(shù)據(jù)保存進(jìn)數(shù)據(jù)庫(kù),為了測(cè)試的需要,在添加數(shù)據(jù)以后,將添加成功與否的結(jié)果顯示在result.jsp上面。
1 public ActionForward execute(ActionMapping mapping, ActionForm form,7,8,9行主要是將content里的空格和回車(chē)符號(hào)轉(zhuǎn)成html中所對(duì)應(yīng)的空格和回車(chē)。
2 HttpServletRequest request, HttpServletResponse response) {
3 NewForm f = (NewForm) form;
4 String sql = "insert into guestbook (name,subject,email,url,content,iconId,password,font,replyId,date,lastReplyTime) " +
5 " values(?,?,?,?,?,?,?,?,-1,now(),now())";
6
7 String content = f.getContent();
8 content = content.replaceAll(" ", " ");
9 content = content.replaceAll("\n", "<br>");
10
11 String params[] = {f.getName(), f.getSubject(), f.getEmail(), f.getUrl(), content, new Integer(f.getIconId()).toString(), f.getPassword(), f.getFont()};
12
13 QueryRunner qr = DbHelper.getQueryRunner();
14
15 String result = null;
16 try {
17 if (qr.update(sql, params) == 1){
18 result = "更新成功";
19 }else{
20 result = "更新失敗";
21 }
22 } catch (SQLException ex) {
23 Logger.getLogger(PostAction.class.getName()).log(Level.SEVERE, null, ex);
24 }
25 f.setResult(result);
26 return mapping.findForward(SUCCESS);
27 }
- 在PostAction.java,IDE自動(dòng)給我們?cè)O(shè)置了一個(gè) private static final String SUCCESS = "success"; 這是為action forward所設(shè)置的forward標(biāo)志,success的名稱(chēng)我們可以自己取,比如我們可以把它改成bbs.post。關(guān)鍵是在結(jié)束對(duì)這個(gè)action class的編程以后,我們需要在struts-config.xml中添加forward聲明。在source editor中打開(kāi)struts-config.xml,右鍵菜單Struts > Add Forward,在Add Forward的面板里如下設(shè)置,按Add完成添加。
ActionForm Bean在Struts里用來(lái)保存網(wǎng)頁(yè)request傳遞之間的數(shù)據(jù)。比如我們現(xiàn)在寫(xiě)的NewForm Bean用來(lái)收集表格內(nèi)的信息,
類(lèi)似于servlet的request.getParamenter()的作用;當(dāng)用戶(hù)提交以后,數(shù)據(jù)將保存在bean內(nèi),然后再做處理。
類(lèi)似于servlet的request.getParamenter()的作用;當(dāng)用戶(hù)提交以后,數(shù)據(jù)將保存在bean內(nèi),然后再做處理。
- 點(diǎn)擊Source Packages > com.bbs.struts,右鍵New > Java Package... 創(chuàng)建一個(gè)com.bbs.struts.form的package用于存放
所有form;
- 右鍵com.bbs.struts.form, New > Struts ActionForm Bean...如果New菜單里沒(méi)有的話(huà),選擇other...,categories里選擇
Struts,F(xiàn)ile types一欄里選擇Struts ActionForm Bean...;
- 為這個(gè)ActionForm取名叫NewForm,然后按Finish完成。
IDE將創(chuàng)建一個(gè)NewForm bean,并在右邊的Source Editor里面打開(kāi)它。默認(rèn)的話(huà),IDE將創(chuàng)造2個(gè)一個(gè)String型的name和int型的number,2個(gè)屬性;并且定義了它們的accessor方法。另外IDE將在struts-config.xml里面,添加對(duì)這個(gè)bean的聲明;
<form-beans>
<form-bean name="NewForm" type="com.bbs.struts.form.NewForm"/>
</form-beans>
- 在Source Editor里面,將原來(lái)的name,number字段刪除,并刪除與之相關(guān)的accessor方法。然后為NewForm添加以下字段,這些字段與之前的post.jsp所用到的字段一一對(duì)應(yīng)。
private String name;利用insert code...功能,添加相應(yīng)的accessor方法。
private String subject;
private String content;
private String url;
private String email;
private int iconId;
private String password;
private String font;
private List icons;
private String result;
- 考慮到因?yàn)閳D標(biāo)的列其實(shí)在生成這個(gè)網(wǎng)頁(yè)的時(shí)候就自動(dòng)添加的,所以在這個(gè)ActionForm bean的Constructor的方法里面,就要處理icon了,還有就是對(duì)字色,網(wǎng)絡(luò)鏈接做一下預(yù)處理:
public NewForm() {
super();
// TODO Auto-generated constructor stub
setUrl("http://");
setFont("#800000");
String sql = "select id,name,src from icon order by id";
QueryRunner qr = DbHelper.getQueryRunner();
List list = null;
try {
list = (List) qr.query(sql, new BeanListHandler(Icon.class));
// TODO Auto-generated constructor stub
} catch (SQLException ex) {
Logger.getLogger(NewForm.class.getName()).log(Level.SEVERE, null, ex);
}
setIcons(list);
}
- 同樣在validate方法里,添加對(duì)subject驗(yàn)證,如果subject為空的話(huà),改名“無(wú)題”。
public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
ActionErrors errors = new ActionErrors();
if (getSubject() == null || getSubject().length() < 1) {
setSubject("無(wú)題");
}
return errors;
}
- 第一個(gè)ActionForm Bean就完成了。
之前的準(zhǔn)備工作完成,現(xiàn)在算是正式進(jìn)入struts項(xiàng)目的環(huán)節(jié)了,首先我們寫(xiě)一個(gè)發(fā)表留言的jsp頁(yè)面。
右鍵點(diǎn)擊BBS項(xiàng)目
, 選擇 New > JSP,命名新文件為post
. 點(diǎn)擊Finish.post.jsp
將在右邊的編輯器里打開(kāi)了。
- 首先在編輯器中,將<title></title>中間的文字改成發(fā)表留言。
- 在文件頂部,添加以下2個(gè)taglib:
<%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>bean tag為用戶(hù)提供了若干tag,主要針對(duì)表單中form bean;html tag用來(lái)代替普通的html標(biāo)簽,達(dá)到簡(jiǎn)化操作的目的。
<%@taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
- 在<body>里面添加:
<html:form action="post">
</html:form> -
從IDE的Palette面板的HTML的分類(lèi)里將Table拉入<html:form action="post">之間,設(shè)置rows
8
, columns2。
在<td>之間添加數(shù)值
<html:form action="post">
<table border="1">
<tbody>
<tr>
<td>名字</td>
<td><html:text property="name" /></d>
</tr>
<tr>
<td>郵件</td>
<td><html:text property="email" /></td>
</tr>
<tr>
<td>題目</td>
<td><html:text property="subject" /> <html:submit value="發(fā)送"/><html:cancel value="重置"/></td>
</tr>
<tr>
<td colspan="2">正文<br>
<html:textarea cols="60" rows="8" property="content" />
</td>
</tr>
<tr>
<td>網(wǎng)站</td>
<td><html:text property="url"/></td>
</tr>
<tr>
<td>圖標(biāo)</td>
<td>
<html:select property="iconId">
<logic:iterate id="icon" name="NewForm" property="icons">
<option value="<bean:write name='icon' property='id'/>"><bean:write name="icon" property="name"/></option>
</logic:iterate>
</html:select>
</td>
</tr>
<tr>
<td>密碼</td>
<td><html:password property="password"/>(英數(shù)8文字內(nèi))</td>
</tr>
<tr>
<td>字色</td>
<td>
<html:radio property="font" value="#800000"><font color="#800000">■</font></html:radio>
<html:radio property="font" value="#DF0000"><font color="#DF0000">■</font></html:radio>
<html:radio property="font" value="#008040"><font color="#008040">■</font></html:radio>
<html:radio property="font" value="#0000FF"><font color="#0000FF">■</font></html:radio>
<html:radio property="font" value="#C100C1"><font color="#C100C1">■</font></html:radio>
<html:radio property="font" value="#FF80C0"><font color="#FF80C0">■</font></html:radio>
<html:radio property="font" value="#FF8040"><font color="#FF8040">■</font></html:radio>
<html:radio property="font" value="#000080"><font color="#000080">■</font></html:radio>
</td>
</tr>
</tbody>
</table>
</html:form>
</body>
第一個(gè)JSP頁(yè)面就完成了。
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>留言板</title>
</head>
<body>
<h1><bean:write name="NewForm" property="result" /></h1>
</body>
</html>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>留言板</title>
</head>
<body>
<h1><bean:write name="NewForm" property="result" /></h1>
</body>
</html>
正如之前所說(shuō)的,開(kāi)發(fā)一個(gè)struts應(yīng)用和一般的web應(yīng)用并沒(méi)有什么兩樣。
1. 創(chuàng)建數(shù)據(jù)庫(kù)
a. guestbook表:用于記錄留言的所有信息
b. ICON表:用于記錄所有的圖標(biāo)記錄
2. JDBC Resource與鏈接池
記得在做上一個(gè)Servlet的項(xiàng)目的時(shí)候,在每個(gè)servlet處理request的時(shí)候(processRequest()方法),都做過(guò)一個(gè)request.setCharacterEncoding("UTF-8")的操作;將request的內(nèi)容轉(zhuǎn)成UTF-8的內(nèi)碼,以解決中文亂碼問(wèn)題。
在Struts的項(xiàng)目里面,我們?nèi)匀粫?huì)遇到中文亂碼問(wèn)題。而我們通過(guò)一個(gè)創(chuàng)建的CharacterEncodingFilter的輔助類(lèi)來(lái)解決問(wèn)題。
4. DbUtils
在處理數(shù)據(jù)連接的問(wèn)題上,還是使用DbUtils這個(gè)類(lèi),詳細(xì)請(qǐng)看Blog系統(tǒng)開(kāi)發(fā) 5. JDBC的基本操作與DbUtils的使用 內(nèi)容。
這里還是寫(xiě)一個(gè)DbHelper的輔助類(lèi),來(lái)簡(jiǎn)化連接的操作。
DbHelper.java
因?yàn)檫@個(gè)bbs的網(wǎng)頁(yè)設(shè)計(jì)是按照日月星辰的留言板的頁(yè)面制作的,所以類(lèi)似icon之類(lèi)的數(shù)據(jù),直接添加到數(shù)據(jù)庫(kù)(假設(shè)所有的icon都在
img 目錄下,icon素材可以直接到星辰去抓的,sql的腳本)
1. 創(chuàng)建數(shù)據(jù)庫(kù)
create database guestbook;
a. guestbook表:用于記錄留言的所有信息
CREATE TABLE `guestbook` (
`id` int(11) NOT NULL AUTO_INCREMENT ,
`name` varchar(40) ,
`email` varchar(60),
`url` varchar(60),
`subject` varchar(200),
`content` varchar(1024),
`font` varchar(100),
`date` datetime ,
`replyId` int(11)DEFAULT '-1' ,
`iconId` int(3),
`lastReplyTime` datetime ,
`password` varchar(16),
PRIMARY KEY (`id`)
);
`id` int(11) NOT NULL AUTO_INCREMENT ,
`name` varchar(40) ,
`email` varchar(60),
`url` varchar(60),
`subject` varchar(200),
`content` varchar(1024),
`font` varchar(100),
`date` datetime ,
`replyId` int(11)DEFAULT '-1' ,
`iconId` int(3),
`lastReplyTime` datetime ,
`password` varchar(16),
PRIMARY KEY (`id`)
);
字段 | 說(shuō)明 |
---|---|
id | 留言編號(hào) |
name | 留言人姓名 |
email地址 | |
url | url地址 |
subject | 留言標(biāo)題 |
content | 留言?xún)?nèi)容 |
iconId | 留言使用的表情圖標(biāo)編號(hào) |
font | 內(nèi)容字體顏色 |
date | 留言時(shí)間 |
replyId | 回復(fù)留言ID,默認(rèn)為-1表示不是回復(fù) |
lastReplyTime | 最近回復(fù)時(shí)間 |
password | 留言所用的密碼(用于編輯) |
b. ICON表:用于記錄所有的圖標(biāo)記錄
CREATE TABLE `icon` (
`id` int(11) NOT NULL AUTO_INCREMENT ,
`name` varchar(20),
`src` varchar(200),
`alt` varchar(100),
PRIMARY KEY (`id`)
);
`id` int(11) NOT NULL AUTO_INCREMENT ,
`name` varchar(20),
`src` varchar(200),
`alt` varchar(100),
PRIMARY KEY (`id`)
);
字段 | 說(shuō)明 |
---|---|
id | 圖標(biāo)編號(hào) |
name | 圖標(biāo)名稱(chēng) |
src | 圖標(biāo)的位置 |
alt | 圖標(biāo)的說(shuō)明 |
2. JDBC Resource與鏈接池
- 給剛剛建的database建立一個(gè)連接,Services標(biāo)簽,點(diǎn)擊Databases的MySql Server at localhost:3306;
- 選擇剛剛建的guestbook,按右鍵點(diǎn)擊connect;我們可以看到在databases的列表里多了jdbc:mysql://localhost:3306/guestbook的鏈接;
- 回到projects標(biāo)簽,點(diǎn)擊項(xiàng)目名稱(chēng)BBS,按右鍵選擇New > Other... 在Categories里面選擇GlassFish;File types項(xiàng)目下面,選擇JDBC Connection Pool,按Next;
- 在New JDBC Connection Pool面板里,JDBC Connection Pool Name里輸入GuestBookPool(隨意),Extract from Existiong Connection的下拉菜單里選擇剛剛建立的database連接jdbc:mysql://localhost:3306/guestbook,
其他設(shè)置使用默認(rèn)值即可,按finish結(jié)束連接池的創(chuàng)建。
- 同樣在Categories里面選擇GlassFish;File types項(xiàng)目下面,選擇JDBC Resource,按Next;
- 在New JDBC Resource面板里,Using Existing JDBC Connection Pool里選擇GuestBookPool(與之前創(chuàng)建的連接池對(duì)應(yīng));
JNDI Name輸入jdbc/bbs(隨意),按finish,完成JDBC Resource配置。
記得在做上一個(gè)Servlet的項(xiàng)目的時(shí)候,在每個(gè)servlet處理request的時(shí)候(processRequest()方法),都做過(guò)一個(gè)request.setCharacterEncoding("UTF-8")的操作;將request的內(nèi)容轉(zhuǎn)成UTF-8的內(nèi)碼,以解決中文亂碼問(wèn)題。
在Struts的項(xiàng)目里面,我們?nèi)匀粫?huì)遇到中文亂碼問(wèn)題。而我們通過(guò)一個(gè)創(chuàng)建的CharacterEncodingFilter的輔助類(lèi)來(lái)解決問(wèn)題。
- CharacterEncodingFilter.java
package com.bbs.struts.util;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
/**
*
* @author Chucky
*/
public class CharacterEncodingFilter implements Filter {
public void init(FilterConfig filterConfig) throws ServletException {
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding("UTF-8");
chain.doFilter(request, response);
}
public void destroy() {
}
}
- 打開(kāi)web.xml,在Filters的面板中添加以下內(nèi)容
4. DbUtils
在處理數(shù)據(jù)連接的問(wèn)題上,還是使用DbUtils這個(gè)類(lèi),詳細(xì)請(qǐng)看Blog系統(tǒng)開(kāi)發(fā) 5. JDBC的基本操作與DbUtils的使用 內(nèi)容。
這里還是寫(xiě)一個(gè)DbHelper的輔助類(lèi),來(lái)簡(jiǎn)化連接的操作。
DbHelper.java
package com.bbs.struts.util;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import org.apache.commons.dbutils.QueryRunner;
/**
*
* @author Chucky
*/
public class DbHelper {
public static QueryRunner getQueryRunner() {
Context context = null;
DataSource ds = null;
try {
context = new InitialContext();
ds = (DataSource) context.lookup("jdbc/bbs");
} catch (NamingException ex) {
Logger.getLogger(DbHelper.class.getName()).log(Level.SEVERE, null, ex);
}
QueryRunner qr = new QueryRunner(ds);
return qr;
}
}
注意context.lookup()中的數(shù)據(jù)源,要與之前的數(shù)據(jù)源匹配。import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import org.apache.commons.dbutils.QueryRunner;
/**
*
* @author Chucky
*/
public class DbHelper {
public static QueryRunner getQueryRunner() {
Context context = null;
DataSource ds = null;
try {
context = new InitialContext();
ds = (DataSource) context.lookup("jdbc/bbs");
} catch (NamingException ex) {
Logger.getLogger(DbHelper.class.getName()).log(Level.SEVERE, null, ex);
}
QueryRunner qr = new QueryRunner(ds);
return qr;
}
}
因?yàn)檫@個(gè)bbs的網(wǎng)頁(yè)設(shè)計(jì)是按照日月星辰的留言板的頁(yè)面制作的,所以類(lèi)似icon之類(lèi)的數(shù)據(jù),直接添加到數(shù)據(jù)庫(kù)(假設(shè)所有的icon都在
img 目錄下,icon素材可以直接到星辰去抓的,sql的腳本)
根據(jù)之前所建立的guestbook表和icon表;現(xiàn)在我們建立Icon類(lèi)和Post類(lèi);
1. Icon類(lèi) Icon.java
在Generate Getter and Setter面板內(nèi),選擇所有的屬性;IDE將自動(dòng)生成setter/getter方法。
同樣建立一個(gè)Post類(lèi),除了原來(lái)guestbook里的字段以外,為了編程的方便再添加一個(gè)Icon的屬性,相當(dāng)于Icon類(lèi)里的src值。
除了以上2個(gè)類(lèi),再建一個(gè)Topic類(lèi),這個(gè)類(lèi)是一個(gè)post和它所有回復(fù)的一個(gè)集合。
1. Icon類(lèi) Icon.java
public class Icon {
private int id;
private String name;
private String src;
private String alt;
}
在Icon.java的Source Editor上按右鍵,點(diǎn)擊Insert Code... 選擇Getter and Setter...;private int id;
private String name;
private String src;
private String alt;
}
在Generate Getter and Setter面板內(nèi),選擇所有的屬性;IDE將自動(dòng)生成setter/getter方法。
同樣建立一個(gè)Post類(lèi),除了原來(lái)guestbook里的字段以外,為了編程的方便再添加一個(gè)Icon的屬性,相當(dāng)于Icon類(lèi)里的src值。
public class Post{
private int id;
private String name;
private String subject;
private String content;
private String url;
private String email;
private int iconId;
private String icon;
private String password;
private Date date;
private Date lastReplyTime;
private int replyId;
private String font;
}
添加相應(yīng)的getter/setter方法。private int id;
private String name;
private String subject;
private String content;
private String url;
private String email;
private int iconId;
private String icon;
private String password;
private Date date;
private Date lastReplyTime;
private int replyId;
private String font;
}
除了以上2個(gè)類(lèi),再建一個(gè)Topic類(lèi),這個(gè)類(lèi)是一個(gè)post和它所有回復(fù)的一個(gè)集合。
public class Topic {
private Post post;
private List replies;
}
添加相應(yīng)的getter/setter方法。private Post post;
private List replies;
}
在使用Netbeans的時(shí)候,除了Struts應(yīng)用所需需要的Struts庫(kù)文件與配置文件以外,創(chuàng)建一個(gè)Struts應(yīng)用與
創(chuàng)建其他任何一個(gè)網(wǎng)絡(luò)應(yīng)用沒(méi)有什么區(qū)別。其實(shí)創(chuàng)建一個(gè)Struts應(yīng)用的方法和任何一個(gè)其他網(wǎng)絡(luò)應(yīng)用的方法
都一樣。
打開(kāi)web.xml,我們可以看一下文件是如何管理Struts的。
創(chuàng)建其他任何一個(gè)網(wǎng)絡(luò)應(yīng)用沒(méi)有什么區(qū)別。其實(shí)創(chuàng)建一個(gè)Struts應(yīng)用的方法和任何一個(gè)其他網(wǎng)絡(luò)應(yīng)用的方法
都一樣。
- 選擇File > New Project. 在Categories里面選擇Web。Projects項(xiàng)目下面,選擇Web Application然后按Next。
- 在輸入項(xiàng)目名稱(chēng)和位置的面板里面,輸入BBS作為項(xiàng)目名稱(chēng),然后按Next;
- 在服務(wù)器與設(shè)置面板里面,選擇選擇一個(gè)你準(zhǔn)備用來(lái)deploy應(yīng)用的服務(wù)器(如:GlassFish v2.1),同時(shí)注意面板下方的
Context Path的路徑與我們的項(xiàng)目名稱(chēng)一致,按Next; - 在Framework面板里,選擇Struts
將Application Resource里的名稱(chēng)com.myapp.struts.ApplicationResource改成com.bbs.struts.ApplicationResource . - 按下Finish,Struts的一個(gè)應(yīng)用就建立完成了。
打開(kāi)web.xml,我們可以看一下文件是如何管理Struts的。
<?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">
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<init-param>
<param-name>debug</param-name>
<param-value>2</param-value>
</init-param>
<init-param>
<param-name>detail</param-name>
<param-value>2</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
<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">
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<init-param>
<param-name>debug</param-name>
<param-value>2</param-value>
</init-param>
<init-param>
<param-name>detail</param-name>
<param-value>2</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>