右邊的Source Editor中,新建的PostAction.java已經打開了;接下來我們要把記錄在NewForm bean里的數據保存進數據庫,為了測試的需要,在添加數據以后,將添加成功與否的結果顯示在result.jsp上面。
1 public ActionForward execute(ActionMapping mapping, ActionForm form,
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 }
7,8,9行主要是將content里的空格和回車符號轉成html中所對應的空格和回車。