選擇java 進入自由開放的國度

          隨筆 - 49, 文章 - 3, 評論 - 154, 引用 - 1
          數據加載中……

          Struts學習心得之Struts流程篇(3) -示例 續

               第二步:實現controller。在Struts中繼承自Action。調用Model,實現數據的深層次檢驗(email是否存在)和數據的插入,程序的跳轉等。代碼如下:

          SignAction.java
           1/**
           2 * @author han
           3 * soochow university
           4 * 實現Action,controller
           5 */

           6public class SignAction extends Action {
           7    
           8     public ActionForward execute(ActionMapping mapping, ActionForm form,
           9                HttpServletRequest request,HttpServletResponse response
          10            ) throws Exception{    
          11         
          12         /*  參數說明:
          13          *  ActionMapping 實現跳轉,控制頁面
          14          *  ActionForm 在viewer中實現的bean,繼承自ActionForm,獲得form中的數據
          15          *  HttpServletRequest   request
          16          *  HttpServeletRsponse  response
          17          */

          18         
          19         ActionErrors errors = new ActionErrors();  //錯誤處理,詳細信息見本blog的《Struts錯誤處理》
          20         
          21         /*
          22          *  得到form中的數據,因為form中的數據在SignForm中,做一類型轉換即可;
          23          *  這個要在struts-config.xml中進行說明
          24          */

          25         SignForm sf = (SignForm) form;
          26         
          27         /*
          28          *  調用Model業務邏輯。
          29          */

          30         SignModel sign = new SignModel();
          31         
          32         sign.setEmail(sf.getEmail());
          33         sign.setUserid(sf.getUserid());
          34         
          35         /*
          36          *  調用Model的findUserByEmail 和 findUserByUserid 判斷
          37          *  email和userid是否存在。
          38          *  如果存在,則添加出錯信息,頁面跳轉到mapping.getInputforward(),需要在
          39          *  struts-config.xml中定義。
          40          *  關于錯誤的詳細信息請參看本blog的《struts錯誤處理》文章。
          41          */

          42         //email existed
          43         if (sign.findUserByEmail()){
          44             errors.add("email.existed",new ActionError("email.existed", sign.getEmail()));
          45             this.saveErrors(request, errors);
          46             return mapping.getInputForward();             
          47         }

          48     
          49         //userid existed
          50         if (sign.findUserByUserid()){
          51             errors.add("userid.existed"new ActionError("userid.existed",sf.getUserid()));
          52             this.saveErrors(request, errors);
          53             return mapping.getInputForward();
          54         }

          55         
          56         /*
          57          * 調用Model的sendPassword將系統生成的密碼發送到用戶信箱。
          58          * 如果發生錯誤轉到mapping.getInputForward(),這個需要在struts-config.xml中定義
          59          * 詳細信息見后面的struts-config.xml文件說明
          60          */

          61         if (sign.sendPassword()){
          62             sign.saveNewUser();
          63         }
          else{  //郵件發送錯誤
          64             errors.add("email.send.error"new ActionError("email.send.error", sf.getEmail()));
          65             this.saveErrors(request, errors);
          66             return mapping.getInputForward();
          67         }

          68                  
          69        /*
          70         *     如果注冊成功,頁面跳轉到mapping.findForward("home")
          71         *  這個需要在struts-config.xml中定義
          72         *  詳細信息見后面的struts-config.xml文件說明
          73         */

          74         return mapping.findForward("home");
          75         
          76         
          77     }

          78}

          說明:
                     1、SignAction實現MVC中的controller,通過mapping參數來實現跳轉,在controller中調用了Model中的一些操作,根據操作結果來實現跳轉。
                      2、程序中包括了Struts的錯誤處理(請見本blog的《struts錯誤處理》)、資源文件的使用,并且好多處代碼都和struts的配置文件struts-config.xml有聯系
                      3、關鍵代碼處都有詳細的注釋,若還有疑問,請您留言,我們共同探討。
               第三步:實現Model,業務邏輯。用戶注冊程序比較簡單,主要實現findUserByUserid()、findUserByEmail()、sendPassword()、saveNewUser()等功能。代碼如下:
              
          SignForm.java 
            1/**
            2 * @author han
            3 * soochow university
            4 * 用戶注冊的Model
            5 */

            6public class SignModel {
            7   private String email;
            8   private String userid;
            9   private String MsgBox = ""
           10   private String password;
           11   private boolean sended;
           12   
           13   
           14/**
           15 * @return Returns the email.
           16 */

           17public String getEmail() {
           18    return email;
           19}

           20/**
           21 * @param email The email to set.
           22 */

           23public void setEmail(String email) {
           24    this.email = email;
           25}

           26/**
           27 * @return Returns the userid.
           28 */

           29public String getUserid() {
           30    return userid;
           31}

           32/**
           33 * @param userid The userid to set.
           34 */

           35public void setUserid(String userid) {
           36    this.userid = userid;
           37}

           38  
           39  //用戶名和email是否存在
           40  public boolean findUserByUserid() throws Exception{
           41      String selectsql = "select userid from password where userid = ?";
           42    Mysql mysql = new Mysql(selectsql);
           43    try{        
           44        mysql.setString(1this.userid);
           45        ResultSet rs = mysql.executeQuery();
           46        if(!rs.next()) return false;
           47    }
           catch (Exception e){
           48        throw new Exception("user.select" + e.getMessage());
           49    }
           finally{
           50        mysql.close();
           51    }
                  
           52    return true;
           53      
           54  }

           55  public boolean findUserByEmail() throws Exception{
           56      String selectsql = "select * from password where email = ?";
           57    Mysql mysql = new Mysql(selectsql);
           58    try{        
           59        mysql.setString(1this.email);
           60        ResultSet rs = mysql.executeQuery();
           61        if(!rs.next()) return false;
           62    }
           catch (Exception e){
           63        throw new Exception("user.select" + e.getMessage());
           64    }
           finally{
           65        mysql.close();
           66    }
                  
           67    return true;
           68  }

           69  
           70  public void saveNewUser() throws HibernateException{
           71      Session session = HibernateUtil.currentSession();      
           72    
           73    Transaction transaction;
           74    try{
           75        transaction = session.beginTransaction();
           76        SignForm newUser = new SignForm();
           77        newUser.setEmail(this.email);
           78        newUser.setUserid(this.userid);
           79        
           80        newUser.setPassword(password);
           81        session.save(newUser);
           82        transaction.commit();
           83    }
          catch(Exception e){
           84        //throw new Exception(e);
           85        e.printStackTrace();
           86    }
          finally{
           87        HibernateUtil.closeSession();
           88    }

           89  }

           90  
           91  //發送email給用戶初始密碼
           92  public boolean sendPassword() throws Exception{
           93           
           94      SendMail sendMail = new SendMail();
           95 
           96      sendMail.setFrom(Constants.FROM);
           97      sendMail.setTo(this.email);
           98      sendMail.setSubject(Constants.SUBJECT);
           99      sendMail.setSmtpHost(Constants.smtpHost);
          100      
          101    //  生成密碼
          102    password = new RandStringGenerator(8).generatorString();
          103      MsgBox = Constants.WELCOME_MESSAGE_HEAD + "\r用戶名:"+this.userid+"\r密碼:" + this.password + "\r" + Constants.WELCOME_MESSAGE_FOOT;
          104      sendMail.setMsgText(MsgBox);
          105      
          106    
          107    
          108      try{
          109          sendMail.sendnow();
          110          sended = true;
          111      }
          catch (Exception e){
          112          System.err.println("send mail error:" + e.getMessage());
          113          //throw new Exception("send mail error" + e.getMessage());
          114          sended = false;
          115       }

          116      return sended;
          117  }

          118}

          說明:
                  1、saveNewUser()使用了Hibernate作為持久化工具,關于Hibernate請參閱相關資料,也可以留言我們共同討論。
                 2、sendPassword()使用JavaMail發送Email,本文件通過SendMail工具類實現。
                 3、密碼生成由RandStringGenerator()工具類生成。
                 4、工具類可以點擊這里下載。

              第四步:配置struts-config.xml。
          <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://struts.apache.org/dtds/struts-config_1_2.dtd">
          <struts-config>
          <global-forwards>   全局轉發
              <!-- 對應SignAction.java 中的return mapping.findForward("home"); -->
            
          <forward name="home" path="/index.jsp"/>
            
          <forward name="userhome" path="/user/userhome.jsp"/>
          </global-forwards>

          <form-beans>
                <!--  bean的聲明,這個在下面的Action設置中要用到  -->
                   <form-bean name="signForm" type="user.SignForm" />
            
          </form-beans>
            
            <!-- 設置Aciton -->
            
          <action-mappings>                                
               
          <action path="/sign"              對應<form action>中action的值,在signin.jsp中的action=/login.do
                      name
          ="signForm"             設置的formBean,名稱對應<from-bean>中的聲明,在SignAction.java中對應輸入參數ActionForm
                      type="user.SignAction"     Action的類
                   validate
          ="true"                  是否驗證
                      scope
          ="request"                作用域   這些應該不用解釋了
                     input
          ="/user/signin.jsp">      當發生錯誤時定向的頁面,對應SignAction.java中的mapping.getInputForward()
                 
               
          </action>
            
          </action-mappings>  
           
            
          <!-- ========== 資源文件定義,詳細信息在《Struts中資源文件使用》中說明=========== -->

            
          <message-resources parameter="Application"/>
            
          </struts-config>

               第五步:調試程序。經過上面的說明和代碼示例是不是對Struts中的MVC架構有了比較清晰的了解,我們知道在java特別是j2ee的軟件中,需要設置很多的配置文件,剛開始的時候非常煩,特別是頻頻出錯的時候,那種感覺學java的人應該都嘗過哦!但是當你徹底了解了配置文件的確切含義,并且能和代碼中的內容進行聯系時,就會豁然開朗了,就不會覺得象走進死胡同似的。

               有了上面struts-config.xml中的說明,相信你已經和代碼聯系起來了,如果將這個程序調試成功,那么你就可以說我已經對struts設計MVC Web程序入門了,一旦跨進了這個門檻,你會覺得學習起來是那么的輕松,一些來得是那么自然。

                好了,希望以上三篇文章能帶你走進Struts,理解Struts,特別是熟悉Struts的基本流程,當然要想對一種模式由深入的了解,必須要多加實踐,從實踐中來體驗到它的好處。

                最后,希望你能徹底了解Struts,能為你所用。如果有什么意見和評論,請留言,我們共同討論,共同進步。
                謝謝你的閱讀!

          posted on 2005-05-19 10:57 soochow_hhb 以java論成敗 以架構論英雄 閱讀(2404) 評論(2)  編輯  收藏 所屬分類: Struts

          評論

          # re: Struts學習心得之Struts流程篇(3) -示例 續  回復  更多評論   

          struts的主要部分是一個controller, 這個controller是一個handler加上一個command模式的實現(就是具體的各個action).
          tomcat監聽來自客戶端的請求, 發現路徑為*.do的請求會發送到struts的handler上, handler根據這個請求的路徑, 查找struts-config的配置, 建立相應的Action子類的對象, 然后調用這個Action類的execute方法.

          action應該是controller的一部分, 不應該實現業務邏輯. 業務邏輯要寫在獨立的model中才可以重用.
          下面是我對mvc的一些理解:
          http://www.cnblogs.com/lane_cn/articles/155254.html
          2005-05-20 14:08 | 小陸

          # re: Struts學習心得之Struts流程篇(3) -示例 續  回復  更多評論   

          您好!我是在baidu里 不小心搜索到你的
          看了你struts里的東西
          很受啟發 很是感謝啊

          覺得自己找到了個牛人
          我以后會經常來的

          希望你以后可以多些這這樣 思路很清晰 帶注釋的j2ee文章給你的崇拜者我啊
          呵呵
          2006-12-17 23:09 | 無敵
          主站蜘蛛池模板: 上犹县| 子洲县| 彰化市| 湖州市| 屏山县| 岳西县| 平凉市| 长汀县| 靖西县| 大足县| 融水| 鹤庆县| 洛扎县| 咸丰县| 金坛市| 青冈县| 水富县| 肇庆市| 枞阳县| 兴隆县| 丰原市| 凯里市| 保康县| 寻乌县| 湖口县| 宁波市| 临漳县| 始兴县| 彩票| 巩义市| 襄垣县| 巴彦淖尔市| 新民市| 洪泽县| 衡南县| 汉川市| 威海市| 张北县| 娄烦县| 宝鸡市| 延庆县|