两亩三分地

  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  17 随笔 :: 20 文章 :: 2 评论 :: 0 Trackbacks
PostAction主要是处理留言添加工作。
  1. 和创建NewForm bean一样,点击Source Packages > com.bbs.struts,右键New > Java Package... 创建一个com.bbs.struts.action的package用于存放所有action类;

  2. 右键com.bbs.struts.action, New > Struts Action...如果New菜单里没有的话,选择other...,categories里选择
    Struts,File types一栏里选择Struts Action ...;

  3. 在New Struts Action面板里面,Class Name填PostAction;Action Path 填/post;按Next


  4. 按照下面的设置,完成对Action的设置


  5. 在struts-config.xml的文档中,IDE自动添加了对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>

  6. 右边的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(" ""&nbsp;");
     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中所对应的空格和回车。

  7. 在PostAction.java,IDE自动给我们设置了一个 private static final String SUCCESS = "success"; 这是为action forward所设置的forward标志,success的名称我们可以自己取,比如我们可以把它改成bbs.post。关键是在结束对这个action class的编程以后,我们需要在struts-config.xml中添加forward声明。在source editor中打开struts-config.xml,右键菜单Struts > Add Forward,在Add Forward的面板里如下设置,按Add完成添加。

按F6 运行项目,浏览器输入:http://localhost:8080/BBS/post.jsp对程序进行测试。如果添加成功的话,下一页将有更新成功的字样。
posted on 2009-10-23 00:31 Chucky 阅读(439) 评论(0)  编辑  收藏 所属分类: BBS Struts项目

只有注册用户登录后才能发表评论。


网站导航: