隨筆-204  評論-149  文章-0  trackbacks-0


           1 package edu.b.recommender.actions;
           2 
           3 import org.apache.struts2.convention.annotation.Action;
           4 import org.apache.struts2.convention.annotation.Actions;
           5 import org.apache.struts2.convention.annotation.Result;
           6 import org.apache.struts2.convention.annotation.Results;
           7 
           8 import com.opensymphony.xwork2.ActionSupport;
           9 
          10 
          11 /*
          12  * 這里的Results是此Action類中的全局跳轉(zhuǎn)路徑
          13  * 如果要配置所有的Action類都能夠用的全局跳轉(zhuǎn)路徑則在struts.xml中配置
          14  *     <!-- 全局results配置 -->
          15          <global-results>
          16         <result name="input">/error.jsp</result>
          17         </global-results>
          18  */
          19 @Results({
          20       @Result(name="index", location="/WEB-INF/page/index.jsp"),
          21       @Result(name="test",  location="/WEB-INF/page/test.jsp")
          22     })
          23 public class HomeAction extends ActionSupport {
          24     
          25     
          26     public String execute() throws Exception{
          27         
          28         //訪問數(shù)據(jù)庫
          29         //獲取首頁中應(yīng)該顯示的數(shù)據(jù)
          30         //怎么從/--->home.action ??????
          31         //home.action---->index.jsp
          32         return "index";
          33     }
          34     
          35     @Action(value="/other/bar",
          36             results={@Result(name = "one", location = "www.baidu.com",type="redirect"),
          37                      @Result(name = "two", location = "/WEB-INF/page/two.jsp")
          38             })
          39     public String myTest(){
          40         String test="dd";
          41         if("dd".equals(test)){
          42             return "one";
          43         }else{
          44             return "two";
          45         }
          46     }
          47     
          48     @Actions({
          49         @Action("/different/url"),
          50         @Action("/another/url")
          51     })
          52     public String newTest(){
          53         return "three";
          54     }
          55     
          56     //使用默認(rèn)的訪問路徑,但是要規(guī)定返回的頁面路徑
          57     //@Results @Result不允許在方法前面使用
          58     //一個(gè)Action不寫value則其默認(rèn)的路徑是什么???????????
          59     @Action(value="home",
          60             results={@Result(name = "home",location="home.action",type="redirect")
          61             })
          62     public String testFour(){
          63         
          64         return "home";
          65     }
          66 
          67 }
          68 

          重點(diǎn)關(guān)注一下type=redirect,redirectAction,chain的區(qū)別
            1package edu.b.recommender.actions;
            2
            3import java.util.Enumeration;
            4import java.util.NoSuchElementException;
            5
            6import javax.servlet.http.HttpServletRequest;
            7import javax.servlet.http.HttpSession;
            8
            9import org.apache.struts2.ServletActionContext;
           10import org.apache.struts2.convention.annotation.Action;
           11import org.apache.struts2.convention.annotation.Actions;
           12import org.apache.struts2.convention.annotation.Result;
           13import org.apache.struts2.convention.annotation.Results;
           14import org.springframework.beans.factory.annotation.Autowired;
           15
           16import com.opensymphony.xwork2.ActionSupport;
           17
           18import edu.b.recommender.common.GlobalConfigure;
           19import edu.b.recommender.po.User;
           20import edu.b.recommender.service.UserManager;
           21
           22/**
           23 * 用戶登錄Action.
           24 * 
           25 * 使用Struts2 convention-plugin annotation定義Action參數(shù).
           26 * 
           27 * @author 
           28 */

           29
           30//在這里加一個(gè)會是什么效果@Action()
           31@Results({
           32    @Result(name="loginSuccessToMymain", location="mymain",type="redirectAction"),
           33    //必須寫成/mymain.action
           34    //@Result(name="loginSuccessToMymain", location="/mymain.action" ,type="dispatcher"),//也不行,是不是應(yīng)該使用chain??
           35    //使用chain可以,但是地址欄上不是顯示新的new.action,chain相當(dāng)于是action的forward,而dispatcher相當(dāng)于是jsp的forward
           36    //forward是不會更新地址欄的中地址,struts1.0中的直接掉轉(zhuǎn)到某個(gè)action其實(shí)就是類似于chain,是不會更改地址欄的地址為新的.do
           37    //@Result(name="loginSuccessToMymain", location="mymain",type="chain"),
           38    @Result(name="loginFailToPrelogin",  location="prelogin", type="redirectAction")
           39    }
          )
           40public class LoginAction extends ActionSupport {
           41    
           42    //使用的服務(wù)類
           43    @Autowired
           44    private UserManager userManager;
           45    
           46//     基本屬性
           47    private String username;
           48    private String password;
           49    
           50    private String returnMessage;
           51    
           52    
           53    /*
           54     * 用戶登錄執(zhí)行的方法
           55     * 表單提交了username ,password兩個(gè)參數(shù),如何獲取這兩個(gè)參數(shù)?
           56     * 1,已經(jīng)將參數(shù)封裝到user的兩個(gè)參數(shù)中了
           57     * 2,通過ActionContext context = ActionContext.getContext()來獲取這兩個(gè)參數(shù)
           58     * 將用戶的參數(shù)保存到session中
           59     */

           60    //默認(rèn)應(yīng)該是login.action--->login.jsp
           61    //實(shí)際讓其跳轉(zhuǎn)到哪里?
           62    public String execute() throws Exception{
           63        return login();
           64    }

           65    
           66    //默認(rèn)返回success時(shí)login!login.action--->login.jsp
           67    //默認(rèn)返回xxxx時(shí)   login!login.action---->login-xxxx.jsp
           68    //能不能將其定義為@Action("login")
           69    public String login() throws Exception{
           70        User userInfo = new User();
           71        userInfo.setUsername(username);
           72        userInfo.setPassword(password);
           73        System.out.println(username+"---------"+password);
           74        //好像這樣查詢查不到
           75        //User tempUser = userManager.checkUser(userInfo);
           76        User tempUser = userManager.checkLogin(username, password);
           77        if(tempUser!=null){
           78            System.out.println(tempUser.getUsername());
           79            
           80            //將用戶保存到session中
           81            
           82            //是否可以用ActionContext來保存
           83//            ActionContext context = ActionContext.getContext();
           84            //Map session = context.getSession();
           85            
           86            HttpServletRequest httpRequest = ServletActionContext. getRequest();
           87            HttpSession httpSession = httpRequest.getSession();
           88            httpSession.setAttribute(GlobalConfigure.USER, tempUser);
           89            returnMessage=tempUser.getUsername()+" ,您已經(jīng)成功登錄到系統(tǒng),歡迎您!";
           90            
           91            //一般的actionMessage是不能在redirect后看到的
           92            //actionMessage在redirect后也看得到的,注意我們的struts.xml里的interceptor stack,加了個(gè)store,就負(fù)責(zé)干這個(gè)事情
           93            //如果直接在重定向的action中獲取之前的頁面請求中的數(shù)據(jù)是不能獲得的
           94            //也可以將returnMessage寫在ActionContext的session Map中,然后不用的時(shí)候一定要自己從session map中remove調(diào)
           95            //但是可以將要顯示的的字符串信息通過如下方法
           96            addActionMessage(returnMessage);
           97            
           98            System.out.println(tempUser);
           99            //返回到用戶的首頁信息,mymain作為類的全局轉(zhuǎn)向
          100            return "loginSuccessToMymain";
          101            
          102        }
          else{
          103            
          104//            用戶名或者密碼錯誤
          105            //需要分開用戶名還是密碼錯誤
          106            userInfo.setUsername(username);
          107            userInfo.setPassword(null);
          108            if(userManager.checkUser(userInfo)==null){
          109                //用戶名錯誤,設(shè)置用戶名錯誤信息
          110                returnMessage="用戶名不存在";
          111                addActionMessage(returnMessage);
          112                
          113            }
          else{
          114                //按用戶名查找正確,則一定是密碼錯誤
          115                returnMessage="用戶名密碼輸入錯誤";
          116                addActionMessage(returnMessage);
          117            }

          118            //返回到用戶的登錄頁面prelogin.action,fail作為此類的全局轉(zhuǎn)向
          119            return "loginFailToPrelogin";
          120        }

          121        
          122    }

          123    
          124
          125    /*
          126     * 注銷登錄,主要是從session中將此用戶的記錄給去掉
          127     * 為什么type不能用redirect-action
          128     */

          129
          130    @Action(value="logout",results={@Result(name = "home",location="home.action",type="redirect")
          131    }
          )
          132    public String logout()throws Exception{
          133        
          134        //ActionContext context = ActionContext.getContext();
          135        //Map session = context.getSession();
          136        HttpServletRequest httpRequest = ServletActionContext. getRequest();
          137        HttpSession httpSession = httpRequest.getSession();
          138        try{
          139            //清空session中的內(nèi)容
          140            Enumeration e = httpSession.getAttributeNames();
          141            for(;e.hasMoreElements();){
          142                System.out.println("session element names:"+e.nextElement());
          143                String elementName = (String)e.nextElement();
          144                httpSession.removeAttribute(elementName);
          145            }

          146        }
          catch(NoSuchElementException e){
          147
          148        }
          catch(Exception e){
          149
          150        }

          151        //銷毀session
          152        httpSession.invalidate();
          153        
          154//        返回到最開始的登錄頁面
          155        return "home";
          156    }

          157    
          158    
          159    
          160    /*
          161     * 用戶注冊,將用戶提交的數(shù)據(jù)保存到數(shù)據(jù)庫中
          162     */

          163    public String register()throws Exception{
          164        return "";
          165    }

          166
          167    
          168    
          169    /* 
          170     *主要用戶頁面的提交轉(zhuǎn)向,沒有實(shí)際的意思 
          171     *不得已最好不要用@Action注釋
          172     *在方法上加@Action相當(dāng)于是給此方法重新定義了action名,參考此文件最好最后注釋
          173     *如果某個(gè)方法需要轉(zhuǎn)向某個(gè)特定的result,則將這個(gè)result作為類的全局轉(zhuǎn)向?qū)懺陬惖那懊?br /> 174     *最好的使用方法還是使用login!prelogin.action來調(diào)用此action,但是返回頁面需要作為類的全局results
          175     *
          176     */

          177    @Action(value="prelogin" ,results={@Result(name="toprelogin",location="/WEB-INF/page/prelogin.jsp")})
          178    public String prelogin() throws Exception {
          179        //這是頁面右上角的東西
          180        //默認(rèn)prelogin.action--->prelogin.jsp
          181        //prelogin!prelogin.action--->prelogin.jsp
          182        //默認(rèn)login!prelogin.action--->login-toprelogin.jsp
          183        return "toprelogin";
          184    }

          185    
          186    
          187    @Action(value="preregister", results={@Result(name="topreregister",location="/WEB-INF/page/preregister.jsp")})    
          188    public String preregister() throws Exception {
          189        //preregister.action-->preregister.jsp
          190        //preregister!preregister.action--->preregister.jsp
          191        //login!preregister.action--->login-topreregister.jsp
          192        return "topreregister";
          193    }

          194    
          195    
          196    
          197    
          198//     基本屬性訪問函數(shù) //
          199
          200    /**
          201     * @return the returnMessage
          202     */

          203    public String getReturnMessage() {
          204        return returnMessage;
          205    }

          206
          207    /**
          208     * @param returnMessage the returnMessage to set
          209     */

          210    public void setReturnMessage(String returnMessage) {
          211        this.returnMessage = returnMessage;
          212    }

          213
          214
          215    /**
          216     * @return the password
          217     */

          218    public String getPassword() {
          219        return password;
          220    }

          221
          222
          223    /**
          224     * @param password the password to set
          225     */

          226    public void setPassword(String password) {
          227        this.password = password;
          228    }

          229
          230
          231    /**
          232     * @return the username
          233     */

          234    public String getUsername() {
          235        return username;
          236    }

          237
          238
          239    /**
          240     * @param username the username to set
          241     */

          242    public void setUsername(String username) {
          243        this.username = username;
          244    }

          245    
          246    
          247    
          248    
          249
          250}

          ******************************************************************************


          1》redirect:action處理完后重定向到一個(gè)視圖資源(如:jsp頁面),請求參數(shù)全部丟失,action處理結(jié)果也全部丟失。
          2》redirect-action:action處理完后重定向到一個(gè)action,請求參數(shù)全部丟失,action處理結(jié)果也全部丟失。
          3》chain:action處理完后轉(zhuǎn)發(fā)到一個(gè)action,請求參數(shù)全部丟失,action處理結(jié)果不會丟失。
          怎么我自己實(shí)驗(yàn)的請求參數(shù)沒有丟失了???? ${username},請求數(shù)據(jù)應(yīng)該不會丟失

          ******************************************************************************

           

          Redirect Action Result:
          這個(gè)Result使用ActionMapperFactory提供的ActionMapper來重定位瀏覽器的URL來調(diào)用指定的action和(可選的)namespace.
          這個(gè)Result比ServletRedirectResult要好.因?yàn)槟悴恍枰裊RL編碼成xwork.xml中配置的ActionMapper提供的模式.
          這就是說你可以在任意點(diǎn)上改變URL模式而不會影響你的應(yīng)用程序. 因此強(qiáng)烈推薦使用這個(gè)Result而不是標(biāo)準(zhǔn)的redirect result來解決重定位到某個(gè)action的情況.
          ActionName (默認(rèn)) - 重定位到的action名
          namespace - action的名稱空間. 如果為null,則為當(dāng)前名稱空間


          Redirect Result
          調(diào)用{@link HttpServletResponse#sendRedirect(String) sendRedirect}方法來轉(zhuǎn)到指定的位置.
          HTTP響應(yīng)被告知使瀏覽器直接跳轉(zhuǎn)到指定的位置(產(chǎn)生客戶端的一個(gè)新請求). 這樣做的結(jié)果會使剛剛執(zhí)行的action(包括action實(shí)例,action中的錯誤消息等)丟失, 不再可用.
          這是因?yàn)閍ction是建立在單線程模型基礎(chǔ)上的. 傳遞數(shù)據(jù)的唯一方式就是通過Session或者可以為Ognl表達(dá)式的web參數(shù)(url?name=value)
          location (默認(rèn)) - action執(zhí)行后跳轉(zhuǎn)的地址.
          parse - 默認(rèn)為true. 如果設(shè)置為false, location參數(shù)不會被當(dāng)作Ognl表達(dá)式解析.

          <result name="success" type="redirect">/displayCart.action?userId=${userId}</result>

          <action   name= "delete "   class= "com.zeng.action.UserManageAction "   method= "delete ">
              <result   type= "redirect "> list.action?pageBean.pageNumber=${pageBean.pageNumber} </result>
          </action>


          *********************************************************************************************************


          今天在用struts2在做項(xiàng)目時(shí)候,從一個(gè)action我想跳轉(zhuǎn)到另一個(gè)action,并且呢得帶上值。說說我的做法吧,首先你得在你的第一個(gè)action中這個(gè)id必須要有set、get方法。
          跳轉(zhuǎn)時(shí)你的struts.xml:
          (方法一):
          <result name="topic" type="redirect">/topicAction!findTopics.do?topicId=${topicId}</result>
          (方法二):
          <result name="topic" type="redirect-action">
            <param name="actionName">findTopics</param>
            <param name="topicId">${topicId}</param>
          </result>

          如果是多個(gè)參數(shù)的話,繼續(xù)再加幾個(gè)<param>就行了,對于(方法一)如果是多個(gè)參數(shù)的怎么辦?
          <result name="topic" type="redirect">/topicAction!findTopics.do?topicId=${topicId}&amp;elementId=${elementId}</result>
          這不就行了。


          ********************************************************************************
          使用redirect重置鏈接需要后綴名,使用了redirect——action就不能使用了,
          就例如使用chain一樣,只需要寫action的配置名,如果加入后綴名.action,就會報(bào)出異常,action未配置正確。

          鍵字: struts2 redirect-action 傳遞 參數(shù)
          ????? 在做一個(gè)系統(tǒng),使用struts2框架,在提交一個(gè)請求后,將獲取的數(shù)據(jù)對象再要生成一個(gè)序列號,為了防止刷新生成冗余序列號,就在請求處理完成后,直接重定向到顯示該信息的action中:

          <action name="enterpreinfo" class="preinfoBusinessAction" method="enterPreinfoSub">
            <result name="success" type="redirect-action">
               showpreinfo?preinfo.order_number=${preinfo.order_number}&amp;preinfo.company_name=${preinfo.company_name}
            </result>
           <result name="error" type="redirect">
           <param name="location">/error.jsp</param>
           </result>
          </action>
          ?因?yàn)槭褂昧藃edirect-action,所以要注意不能將showpreinf?preinfo.order_number=${preinfo.order_number}寫成showpreinf.action?preinfo.order_number=${preinfo.order_number}

          在這個(gè)配置文件里,多個(gè)參數(shù)的連接符使用了"&amp;",但XML的語法規(guī)范,應(yīng)該使用"&amp;"代替"&",原理和HTML中的轉(zhuǎn)義相同,開始沒有注意,在struts分析配置文件時(shí),總是報(bào)出這樣的錯誤:

          The reference to entity "preinfo" must end with the ';' delimiter.

          ?

          進(jìn)行上面說明的替換后,就正常了。

           

          ************************************************************************************
          This is how I should do it

          @Results({
              @Result(name="input", type="redirectAction", params = {"actionName" , "resend"})
          })


          *************************************************************************************
          http://corradignw.javaeye.com/blog/355717


          struts2.1.6無論是xml還是annotation配置redirectAction時(shí),如果要傳一些參數(shù),
          可是這些參數(shù)在ServletActionRedirectResult并沒有聲明,這時(shí)ognl會拋異常出來。
          但實(shí)際上傳值是成功的。詳見struts2的jira:
          例:
          Java代碼
          @Results({  
              @Result(name="reload",type="redirectAction" 
              ,params={"actionName","hello_world" 
                      ,"namespace","/center/part1" 
                      ,"id","09" 
                      ,"count","90"})  
          }) 

          @Results({
              @Result(name="reload",type="redirectAction"
           ,params={"actionName","hello_world"
                ,"namespace","/center/part1"
                ,"id","09"
                ,"count","90"})
          })


          把日志級別調(diào)高也不管用,好像還沒有什么解決辦法。

           


          ****************************************************************************************
          dispatcher 結(jié)果類型為缺省的result類型,用于返回一個(gè)視圖資源(如:jsp)
          Xml代碼 :

          <result name="success">/main.jsp</result>
          <result name="success">/main.jsp</result>
          以上寫法使用了兩個(gè)默認(rèn),其完整的寫法為:
             <result name="success" type="dispatcher">
               <param name="location">/maini.jsp</param>
          </result>
          location只能是頁面,不能是另一個(gè)action(可用type="chain"解決)。

          redirect 結(jié)果類型用于重定向到一個(gè)頁面,另一個(gè)action或一個(gè)網(wǎng)址。
          Xml代碼:

          <result name="success" type="redirect">aaa.jsp</result>
          <result name="success" type="redirect">bbb.action</result>
          <result name="success" type="redirect">www.baidu.com</result>

          redirect-action 結(jié)果類型使用ActionMapperFactory提供的ActionMapper來重定向請求到另外一個(gè)action
          Xml代碼:

          <result name="err" type="redirect-action">
              <param name="actionName">重定向的Action名</param>
               <param name="namespace">重定向Action所在的名字空間</param>
          </result>
          redirect和redirect-action兩種結(jié)果類型在使用上其實(shí)并沒有什么區(qū)別,只是寫法不同而已。

          chain 用于把相關(guān)的幾個(gè)action連接起來,共同完成一個(gè)功能。
          Xml代碼:

          <action name="step1" class="test.Step1Action">
               <result name="success" type="chain">step2.action</result>
          </action>
          <action name="step2" class="test.Step2Action">
          <result name="success">finish.jsp</result>
          </action>
          處于chain中的action屬于同一個(gè)http請求,共享一個(gè)ActionContext
           
          plaintextj 結(jié)果類型用于直接在頁面上顯示源代碼

          Xml代碼:

          <result name="err" type="plaintext">
              <param name="location">具體的位置</param>
              <param name="charSet">字符規(guī)范(如GBK)</param>
          </result>

          posted on 2009-05-03 20:09 Frank_Fang 閱讀(25245) 評論(6)  編輯  收藏 所屬分類: SSH+JQuery+DWR

          評論:
          # re: Struts 注解配置例子及redirect,redirectAction,chain的區(qū)別[未登錄] 2009-06-11 14:15 | jack
          不錯,有點(diǎn)明白了  回復(fù)  更多評論
            
          # re: Struts 注解配置例子及redirect,redirectAction,chain的區(qū)別[未登錄] 2009-11-05 14:57 | zlcisonly
          很不錯的文章  回復(fù)  更多評論
            
          # re: Struts 注解配置例子及redirect,redirectAction,chain的區(qū)別 2010-03-26 10:54 | 打點(diǎn)滴
          我頂   回復(fù)  更多評論
            
          # re: Struts 注解配置例子及redirect,redirectAction,chain的區(qū)別[未登錄] 2010-05-12 12:58 | 過客
          請問下你帶的參數(shù)是中文如何處理,例如"name"="中國人"  回復(fù)  更多評論
            
          # re: Struts 注解配置例子及redirect,redirectAction,chain的區(qū)別 2011-04-15 12:07 |
          <result name="action{2}" type="redirectAction">
          <param name="actionName">Product</param>
          <param name="type">admin</param>
          </result>

          重定向到Action,相當(dāng)于<a href="Product.action?type=admin">提交</a>  回復(fù)  更多評論
            
          # re: Struts 注解配置例子及redirect,redirectAction,chain的區(qū)別[未登錄] 2012-05-16 15:59 | aaa
          胡錦濤  回復(fù)  更多評論
            
          主站蜘蛛池模板: 蒙山县| 孟连| 交城县| 鱼台县| 巴里| 遂宁市| 南木林县| 安阳市| 双鸭山市| 永吉县| 嘉峪关市| 临夏市| 遂平县| 临邑县| 安远县| 阿尔山市| 萨迦县| 福鼎市| 聂荣县| 寻乌县| 贡觉县| 溧阳市| 邵东县| 尼勒克县| 宁德市| 大冶市| 青海省| 托克托县| 鹤壁市| 顺昌县| 瑞昌市| 南部县| 越西县| 汶川县| 普格县| 岳阳县| 仁化县| 永定县| 浦江县| 阳城县| 宁武县|