struts2--(3)--一些小知识点---result

struts2中的result配置。

1.result的type属性,常用的有四种:

--dispatcher类型 

Includes or forwards to a view (usually a jsp). Behind the scenes Struts will use a RequestDispatcher, where the target servlet/JSP receives the same request/response objects as the original servlet/JSP. Therefore, you can pass data between them using request.setAttribute() - the Struts action is available.(由于使用的是forward,因此它是在服务器端调转的,request和response对象还是原来的,因此forward前后的jsp页面可以用request.setAttribute来传输数据)

There are three possible ways the result can be executed:

    • If we are in the scope of a JSP (a PageContext is available), PageContext's {@link PageContext#include(String) include} method is called.

    • If there is no PageContext and we're not in any sort of include (there is no "javax.servlet.include.servlet_path" in the request attributes), then a call to {@linkRequestDispatcher#forward(javax.servlet.ServletRequest, javax.servlet.ServletResponse) forward} is made.

    • Otherwise, {@link RequestDispatcher#include(javax.servlet.ServletRequest, javax.servlet.ServletResponse) include} is called。

    Parameters

      • location (default) - the location to go to after execution (ex. jsp).

      • parse - true by default. If set to false, the location param will not be parsed for Ognl expressions.

      Examples

      < result name="success" type="dispatcher">
         < param name="location">foo.jsp</ param >
      </ result >

          --- Redirect类型

      Calls the {@link HttpServletResponse#sendRedirect(String) sendRedirect} method to the location specified. The response is told to redirect the browser to the specified location (a new request from the client). The consequence of doing this means that the action (action instance, action errors, field errors, etc) that was just executed is lost and no longer available. This is because actions are built on a single-thread model. The only way to pass data is through the session or with web parameters (url?name=value) which can be OGNL expressions.(和dispatch不同的是,它实现的是在客服端进行调转,它会重新创建一个request和response对象,因此跳转前后不能通过request.setAttribute来传输数据,而需要使用session来传输数据或者在web页面上使用parameter方法来传输数据了

      Parameters

        • location (default) - the location to go to after execution.

        • parse - true by default. If set to false, the location param will not be parsed for Ognl expressions.

        • anchor - Optional. Also known as "fragment" or colloquially as "hash". You can specify an anchor for a result.

        This result follows the same rules from StrutsResultSupport.

        Examples

        <!--
           The redirect URL generated will be:
           /foo.jsp#FRAGMENT
        -->
        < result name="success" type="redirect">
           < param name="location">foo.jsp</ param >
           < param name="parse">false</ param >
           < param name="anchor">FRAGMENT</ param >
        </ result >
        < package name="passingRequestParameters" extends ="struts- default " namespace="/passingRequestParameters">
            <-- Pass parameters (reportType, width and height) -->
            <!--
            The redirect url generated will be - the namespace of current acction will be appended as location doesn&# 39 ;t start with "/":
            /passingRequestParameters/generateReport.jsp?reportType=pie&width= 100 &height= 100 #summary
            -->
            <action name="gatherReportInfo" class ="...">
               <result name="showReportResult" type="redirect">
                  <param name="location">generateReport.jsp</param>
                  <param name="reportType">pie</param>
                  <param name="width"> 100 </param>
                  <param name="height"> 100 </param>
                  <param name="parse"> false </param>
                  <param name="anchor">summary</param>
               </result>
            </action>
        </ package >
            上面两种类型,result都是针对视图调转的,不能针对action跳转。下面两种方法是针对action来跳转的。
            
        ----Chain 类型

        This result invokes an entire other action, complete with it's own interceptor stack and result.(新的action,他会创建新的value stack,它是在服务器端跳转的,还是同一个request和response)

        Parameters

          • actionName (default) - the name of the action that will be chained to

          • namespace - used to determine which namespace the Action is in that we're chaining.If namespace is null, this defaults to the current namespace

          • method - used to specify another method on target action to be invoked.If null, this defaults to execute method

          • skipActions - (optional) the list of comma separated action names for the actions that could be chained to

          Examples


          < package name="public" extends="struts-default">
               <!-- Chain creatAccount to login, using the default parameter -->
               < action name="createAccount" class="...">
                   < result type="chain">login</ result >
               </ action >
           
               < action name="login" class="...">
                   <!-- Chain to another namespace -->
                   < result type="chain">
                       < param name="actionName">dashboard</ param >
                       < param name="namespace">/secure</ param >
                   </ result >
               </ action >
          </ package >
           
          < package name="secure" extends="struts-default" namespace="/secure">
               < action name="dashboard" class="...">
                   < result >dashboard.jsp</ result >
               </ action >
          </ package >

            ---- RedirectAction类型

          This result uses the ActionMapper provided by the ActionMapperFactory to redirect the browser to a URL that invokes the specified action and (optional) namespace. This is better than the ServletRedirectResult because it does not require you to encode the URL patterns processed by the ActionMapper in to your struts.xml configuration files. This means you can change your URL patterns at any point and your application will still work. It is strongly recommended that if you are redirecting to another action, you use this result rather than the standard redirect result.(它属于客户端跳转,将从新生成一个新的request和response)

          See examples below for an example of how request parameters could be passed in.

          Icon

          See ActionMapper for more details

          Parameters

            • actionName (default) - The name of the action that will be redirected to.

            • namespace - Used to determine which namespace the action is in that we're redirecting to.If namespace is null, the default will be the current namespace.

            • suppressEmptyParameters - Optional boolean (defaults to false) that can prevent parameters with no values from being included in the redirect URL.

            • parse - Boolean, true by default. If set to false, the actionName param will not be parsed for Ognl expressions.

            • anchor - Optional. Also known as "fragment" or colloquially as "hash". You can specify an anchor for a result.

            Examples

            < package name="public" extends="struts-default">
                 < action name="login" class="...">
                     <!-- Redirect to another namespace -->
                     < result type="redirectAction">
                         < param name="actionName">dashboard</ param >
                         < param name="namespace">/secure</ param >
                     </ result >
                 </ action >
            </ package >
             
            < package name="secure" extends="struts-default" namespace="/secure">
                 <-- Redirect to an action in the same namespace -->
                 < action name="dashboard" class="...">
                     < result >dashboard.jsp</ result >
                     < result name="error" type="redirectAction">error</ result >
                 </ action >
             
                 < action name="error" class="...">
                     < result >error.jsp</ result >
                 </ action >
            </ package >
             
            < package name="passingRequestParameters" extends="struts-default" namespace="/passingRequestParameters">
                <!-- Pass parameters (reportType, width and height) -->
                <!--
                The redirectAction url generated will be :
                /genReport/generateReport.action?reportType=pie&width=100&height=100#summary
                -->
                < action name="gatherReportInfo" class="...">
                   < result name="showReportResult" type="redirectAction">
                      < param name="actionName">generateReport</ param >
                      < param name="namespace">/genReport</ param >
                      < param name="reportType">pie</ param >
                      < param name="width">100</ param >
                      < param name="height">100</ param >
                      < param name="empty"></ param >
                      < param name="suppressEmptyParameters">true</ param >
                      < param name="anchor">summary</ param >
                   </ result >
                </ action >
            </ package >
            <!--
                 Example of "anchor" param usage in conjunction with "redirectAction" result-type.
             
                 Generated URL: /displayReport.action#SUMMARY
            -->
             
            < action name="displayReport">
                 < result >/jsp/displayReport.jsp</ result >
            </ action >
             
            < action name="financeReport" class="com.mycompany.reports.FinanceReportAction">
                 < result name="input">/jsp/index.jsp</ result >           
                 < result name="success" type="redirectAction">
                     < param name="actionName">displayReport</ param >
                     < param name="parse">false</ param >
                     < param name="anchor">SUMMARY</ param >
                 </ result >
            </ action >

            2.全局result配置

            Global Results

            Most often, results are nested with the action element. But some results apply to multiple actions. In a secure application, a client might try to access a page without being authorized, and many actions may need access to a "logon" result.

            If actions need to share results, a set of global results can be defined for each package. The framework will first look for a local result nested in the action. If a local match is not found, then the global results are checked.(有些result是很多action可以共用的,这种result可以写在全局result配置中,当它在action中找不到指定的result时,将会使用global result中对应的result,需要注意的是,每个package都可以有一个独立的global result,但是当有些result是很通用的,可以将这些result配置在一个特殊的package中,其它新定义的package则只要继承这个package就行)

            Defining global results
            < global-results >
                 < result name="error">/Error.jsp</ result >
                 < result name="invalid.token">/Error.jsp</ result >
                 < result name="login" type="redirectAction">Logon!input</ result >
            </ global-results >

            <struts>
                <constant name="struts.devMode" value="true" />
                <package name="user" namespace="/user" extends="struts-default">
                	
                	
                	<global-results>
                		<result name="mainpage">/main.jsp</result>
                	</global-results>
                	
                	<action name="index">
                		<result>/index.jsp</result>
                	</action>
                	
            	    <action name="user" class="com.bjsxt.struts2.user.action.UserAction">
            	    	<result>/user_success.jsp</result>
            	    	<result name="error">/user_error.jsp</result>
            	    </action>	    
                </package>
                <!--使用extends可以是下面这个package也可以共用上面package定义的global result配置 -->
                <package name="admin" namespace="/admin" extends="user">
                	<action name="admin" class="com.bjsxt.struts2.user.action.AdminAction">
                		<result>/admin.jsp</result>
                	</action>
                </package>
            </struts>


                 ---Dynamic类型

            A result may not be known until execution time. Consider the implementation of a state-machine-based execution flow; the next state might depend on any combination of form input elements, session attributes, user roles, moon phase, etc. In other words, determining the next action, input page, etc. may not be known at configuration time.(动态结果类型,是指只有在运行时才知道调转到那个视图页面,因此在配置文件中没法直接指定,这个时候可以采用EL表达式,来获取Action中的返回的调转页面,如下面的例子:${nextAction}, 但是需要注意的是在action中需要有一个String类型的属性,它用来保存action返回的视图名,这个属性需要有set和get方法)

            Result values may be retrieved from its corresponding Action implementation by using EL expressions that access the Action's properties, just like the Struts 2 tag libraries. So given the following Action fragment:

            FragmentAction implementation
            private String nextAction;
             
            public String getNextAction() {
                 return nextAction;
            }

            you might define a result like this:

            FragmentAction configuration
            < action name="fragment" class="FragmentAction">
                 < result name="next" type="redirectAction">${nextAction}</ result >
            </ action >

            If a FragmentAction method returns "next" the actual value of that result will be whatever is in FragmentAction's nextAction property. So nextAction may be computed based on whatever state information necessary then passed at runtime to "next"'s redirectAction.

            下面是一个例子:

            public class UserAction extends ActionSupport {
            	private int type;
            	
            	private String r;
            
            	public String getR() {
            		return r;
            	}
            
            	public void setR(String r) {
            		this.r = r;
            	}
            
            	public int getType() {
            		return type;
            	}
            
            	public void setType(int type) {
            		this.type = type;
            	}
            
            	@Override
            	public String execute() throws Exception {
            		if(type == 1) r="/user_success.jsp";
            		else if (type == 2) r="/user_error.jsp";
            		return "success";
            	}
            }
            struts.xml配置如下:


            <struts>
                <constant name="struts.devMode" value="true" />
                <package name="user" namespace="/user" extends="struts-default">
                	
            	    <action name="user" class="com.bjsxt.struts2.user.action.UserAction">
            	    	<result>${r}</result>
            	    </action>	    
                </package>
                	
            </struts>


            ---Parameters in configuration results(带参数类型的result)

            Sometimes there is a need to redirect from one action to another, but you do not know the exact URL or that the destination URL requires parameters that are only known at run-time.(带参数类型的result,也就是说当要调转到另外一个action时,这个action属于另外一个请求,由于两个不同的请求不能共享同一个value stack, 因此需要从当前这个action中传一些参数到将要跳转的action)

            Struts 2 offers an easy solution for that problem.

            Parameters in action result definitions

            < struts >
            ...
                < package name="somePackage" namespace="/myNamespace" extends="struts-default">
                   < action name="myAction" class="com.project.MyAction">
                      < result name="success" type="redirectAction">otherAction?id=${id}</ result >
                      < result name="back" type="redirect">${redirectURL}</ result >
                   </ action >
             
                   < action name="otherAction" class="com.project.MyOtherAction">
                      ...
                   </ action >     
                </ package >
            ...
            </ struts >

            The only requirement is to declare the necessary properties in your action, in this case com.project.MyAction should define properties id and redirectURL with standard accessor methods.(需要在action中定义相应的属性,具有get和set方法,这样在struts.xml中可以通过EL表达式来获取该属性值,如下面的id和redirectURL)

            public class MyAction extends ActionSupport {
                private int id;
                private String redirectURL;
                ...
             
             
                public String execute() {
                    ...
                   if (someCondition) {
                      this .redirectURL = "/the/target/page.action";
                      return "back";
                   }
             
                   this .id = 123 ;
                   return SUCCESS;
                }
             
                public int getId() { return this .id; }
                public void setId( int id) { this .id = id; }
                public String getRedirectURL() { return this .redirectURL; }
                public void setRedirectURL(String redirectURL) { this .redirectURL= redirectURL; }
                ...
            }

            In the above code if it returns SUCCESS then the browser will be forwarded to
            /<app-prefix>/myNamespace/otherAction.action?id=123




            评论
            添加红包

            请填写红包祝福语或标题

            红包个数最小为10个

            红包金额最低5元

            当前余额3.43前往充值 >
            需支付:10.00
            成就一亿技术人!
            领取后你会自动成为博主和红包主的粉丝 规则
            hope_wisdom
            发出的红包
            实付
            使用余额支付
            点击重新获取
            扫码支付
            钱包余额 0

            抵扣说明:

            1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
            2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

            余额充值