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

          具有豐富知識和經(jīng)驗的人,比只有一種知識和經(jīng)驗的人更容易產(chǎn)生新的聯(lián)想和獨到的見解。
          隨筆 - 49, 文章 - 3, 評論 - 154, 引用 - 1

          導(dǎo)航

          <2025年6月>
          25262728293031
          1234567
          891011121314
          15161718192021
          22232425262728
          293012345

          常用鏈接

          留言簿(9)

          隨筆分類(43)

          隨筆檔案(49)

          文章分類(2)

          文章檔案(3)

          相冊

          收藏夾(1)

          java開源項目

          • Hibernate插件 Synchronizer
          • 根據(jù)mappingfile自動產(chǎn)生java代碼The automaticallly generated objects include: Value Objects Proxy Interfaces Composite Key Objects Enumeration Objects Component Objects Subclasses DAOs Other features include: Editor with code assist and outline view Custom template generation New mapping file wizard that queries your database New configuration file wizard Actions for adding mapping references, synchronizing files, and manually activating code generation
          • Junit
          • Struts
          • apache開源基金的MVC框架

          Reading

          搜索

          •  

          積分與排名

          • 積分 - 107638
          • 排名 - 546

          最新評論

          閱讀排行榜

          評論排行榜

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

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

          SignAction.java
           1/**
           2 * @author han
           3 * soochow university
           4 * 實現(xiàn)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         /*  參數(shù)說明:
          13          *  ActionMapping 實現(xiàn)跳轉(zhuǎn),控制頁面
          14          *  ActionForm 在viewer中實現(xiàn)的bean,繼承自ActionForm,獲得form中的數(shù)據(jù)
          15          *  HttpServletRequest   request
          16          *  HttpServeletRsponse  response
          17          */

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

          25         SignForm sf = (SignForm) form;
          26         
          27         /*
          28          *  調(diào)用Model業(yè)務(wù)邏輯。
          29          */

          30         SignModel sign = new SignModel();
          31         
          32         sign.setEmail(sf.getEmail());
          33         sign.setUserid(sf.getUserid());
          34         
          35         /*
          36          *  調(diào)用Model的findUserByEmail 和 findUserByUserid 判斷
          37          *  email和userid是否存在。
          38          *  如果存在,則添加出錯信息,頁面跳轉(zhuǎn)到mapping.getInputforward(),需要在
          39          *  struts-config.xml中定義。
          40          *  關(guān)于錯誤的詳細信息請參看本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          * 調(diào)用Model的sendPassword將系統(tǒng)生成的密碼發(fā)送到用戶信箱。
          58          * 如果發(fā)生錯誤轉(zhuǎn)到mapping.getInputForward(),這個需要在struts-config.xml中定義
          59          * 詳細信息見后面的struts-config.xml文件說明
          60          */

          61         if (sign.sendPassword()){
          62             sign.saveNewUser();
          63         }
          else{  //郵件發(fā)送錯誤
          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         *     如果注冊成功,頁面跳轉(zhuǎn)到mapping.findForward("home")
          71         *  這個需要在struts-config.xml中定義
          72         *  詳細信息見后面的struts-config.xml文件說明
          73         */

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

          78}

          說明:
                     1、SignAction實現(xiàn)MVC中的controller,通過mapping參數(shù)來實現(xiàn)跳轉(zhuǎn),在controller中調(diào)用了Model中的一些操作,根據(jù)操作結(jié)果來實現(xiàn)跳轉(zhuǎn)。
                      2、程序中包括了Struts的錯誤處理(請見本blog的《struts錯誤處理》)、資源文件的使用,并且好多處代碼都和struts的配置文件struts-config.xml有聯(lián)系
                      3、關(guān)鍵代碼處都有詳細的注釋,若還有疑問,請您留言,我們共同探討。
               第三步:實現(xiàn)Model,業(yè)務(wù)邏輯。用戶注冊程序比較簡單,主要實現(xiàn)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  //發(fā)送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作為持久化工具,關(guān)于Hibernate請參閱相關(guān)資料,也可以留言我們共同討論。
                 2、sendPassword()使用JavaMail發(fā)送Email,本文件通過SendMail工具類實現(xiàn)。
                 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>   全局轉(zhuǎn)發(fā)
              <!-- 對應(yīng)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設(shè)置中要用到  -->
                   <form-bean name="signForm" type="user.SignForm" />
            
          </form-beans>
            
            <!-- 設(shè)置Aciton -->
            
          <action-mappings>                                
               
          <action path="/sign"              對應(yīng)<form action>中action的值,在signin.jsp中的action=/login.do
                      name
          ="signForm"             設(shè)置的formBean,名稱對應(yīng)<from-bean>中的聲明,在SignAction.java中對應(yīng)輸入?yún)?shù)ActionForm
                      type="user.SignAction"     Action的類
                   validate
          ="true"                  是否驗證
                      scope
          ="request"                作用域   這些應(yīng)該不用解釋了
                     input
          ="/user/signin.jsp">      當發(fā)生錯誤時定向的頁面,對應(yīng)SignAction.java中的mapping.getInputForward()
                 
               
          </action>
            
          </action-mappings>  
           
            
          <!-- ========== 資源文件定義,詳細信息在《Struts中資源文件使用》中說明=========== -->

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

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

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

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

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

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

          評論

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

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

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

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

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

          覺得自己找到了個牛人
          我以后會經(jīng)常來的

          希望你以后可以多些這這樣 思路很清晰 帶注釋的j2ee文章給你的崇拜者我啊
          呵呵
          2006-12-17 23:09 | 無敵
          主站蜘蛛池模板: 通榆县| 香河县| 湘潭市| 亚东县| 柏乡县| 浮山县| 晋宁县| 济阳县| 岗巴县| 江源县| 乌鲁木齐市| 安化县| 西盟| 沈阳市| 涪陵区| 成安县| 五指山市| 伊通| 沂南县| 龙里县| 遂平县| 彝良县| 赤城县| 永吉县| 嘉峪关市| 墨玉县| 夹江县| 云梦县| 西乌珠穆沁旗| 万盛区| 云和县| 石景山区| 辽宁省| 黔西县| 获嘉县| 平顺县| 茂名市| 新竹市| 万宁市| 青川县| 长宁区|