PostAction主要是處理留言添加工作。
- 和創(chuàng)建NewForm bean一樣,點(diǎn)擊Source Packages > com.bbs.struts,右鍵New > Java Package... 創(chuàng)建一個(gè)com.bbs.struts.action的package用于存放所有action類;
- 右鍵com.bbs.struts.action, New > Struts Action...如果New菜單里沒(méi)有的話,選擇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)打開了;接下來(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里的空格和回車符號(hào)轉(zhuǎn)成html中所對(duì)應(yīng)的空格和回車。
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的名稱我們可以自己取,比如我們可以把它改成bbs.post。關(guān)鍵是在結(jié)束對(duì)這個(gè)action class的編程以后,我們需要在struts-config.xml中添加forward聲明。在source editor中打開struts-config.xml,右鍵菜單Struts > Add Forward,在Add Forward的面板里如下設(shè)置,按Add完成添加。