刨根問底-struts-自定義Result的返回type類型

struts.xml配置action的相應信息: java


<struts>
	
	<package name="manage" extends="default" namespace="/manage">
		<action name="pici" class="com.xing.action.crawl.PiciAction" method="pici">
			<result name="success" >/WEB-INF/crawl/success.jsp</result>
			<result name="error" >/WEB-INF/web/error.jsp</result>
		</action>
....
result標籤訂義action執行完成後跳轉的方向。result標籤的type類型默認是dispatcher 用來呈現JSP頁面。下面咱們來自定義一個type類型。


一、開發自定義Result是很是簡單的,只須要實現com.opensymphony.xwork2.Result接口就能夠了,這裏也想同時觀察一下ServletDispatcherResult,因此咱們就定義ServletDispatcherResult web

package test.dispatcher;

import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.PageContext;

import org.apache.commons.lang.ObjectUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.StrutsResultSupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.opensymphony.xwork2.ActionInvocation;


 * <!-- START SNIPPET: description -->
public class ServletDispatcherResult extends StrutsResultSupport {

    private static final long serialVersionUID = -1970659272360685627L;

    private static final Logger LOG = LoggerFactory.getLogger(ServletDispatcherResult.class);

    public ServletDispatcherResult() {
        super();
    }

    public ServletDispatcherResult(String location) {
        super(location);
    }

    /**
     * Dispatches to the given location. Does its forward via a RequestDispatcher. If the
     * dispatch fails a 404 error will be sent back in the http response.
     *
     * @param finalLocation the location to dispatch to.
     * @param invocation    the execution state of the action
     * @throws Exception if an error occurs. If the dispatch fails the error will go back via the
     *                   HTTP request.
     */
    public void doExecute(String finalLocation, ActionInvocation invocation) throws Exception {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Forwarding to location " + finalLocation);
        }

        PageContext pageContext = ServletActionContext.getPageContext();

        if (pageContext != null) {
            pageContext.include(finalLocation);
        } else {
            HttpServletRequest request = ServletActionContext.getRequest();
            HttpServletResponse response = ServletActionContext.getResponse();
            RequestDispatcher dispatcher = request.getRequestDispatcher(finalLocation);

            //add parameters passed on the location to #parameters
            // see WW-2120
            if (invocation != null && finalLocation != null && finalLocation.length() > 0
                    && finalLocation.indexOf("?") > 0) {
                String queryString = finalLocation.substring(finalLocation.indexOf("?") + 1);
                Map parameters = (Map) invocation.getInvocationContext().getContextMap().get("parameters");
//                Map queryParams = UrlHelper.parseQueryString(queryString, true);
//                if (queryParams != null && !queryParams.isEmpty())
//                    parameters.putAll(queryParams);
            }

            // if the view doesn't exist, let's do a 404
            if (dispatcher == null) {
                response.sendError(404, "result '" + finalLocation + "' not found");

                return;
            }
//  public static final String STRUTS_ACTION_TAG_INVOCATION= "struts.actiontag.invocation";
            //if we are inside an action tag, we always need to do an include
            Boolean insideActionTag = (Boolean) ObjectUtils.defaultIfNull(request.getAttribute("struts.actiontag.invocation"), Boolean.FALSE);

            // If we're included, then include the view
            // Otherwise do forward
            // This allow the page to, for example, set content type
            if (!insideActionTag && !response.isCommitted() && (request.getAttribute("javax.servlet.include.servlet_path") == null)) {
                request.setAttribute("struts.view_uri", finalLocation);
                request.setAttribute("struts.request_uri", request.getRequestURI());

                dispatcher.forward(request, response);
            } else {
                dispatcher.include(request, response);
            }
        }
    }
}

在這裏finalLocation值:/gaokao/WEB-INF/index.jsp apache

request.getRequestURI()值:/WEB-INF/index.jsp jsp

二、而後在struts.xml文件中配置一下 ide

<package name="default" extends="struts-default">
		<result-types>
			<result-type name="myDispatcher" class="test.dispatcher.ServletDispatcherResult" default="false"/>
		</result-types>
三、使用自定義的type類型myDispatcher,例如:
<action name="login" class="com.xing.action.UserAction" method="login">
			<result name="success" type="myDispatcher">/WEB-INF/index.jsp</result>
			<result name="error" >/WEB-INF/login.jsp</result>
		</action>

到這裏,主要的代碼已經寫完了。 spa

相關文章
相關標籤/搜索