1
配置文件:
<result name="success" type="dispatcher">
<param name="location">foo.jsp</param>
</result>
如果没有写type类型,默认的是dispatcher(就在下面这一行设置的),请看struts-default.xml
拦截器:
<result-type name="dispatcher" class="org.apache.struts2.dispatcher.ServletDispatcherResult" default="true"/>
ServletDispatcherResult的代码:
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) {//如果在jsp范围内(pageContext有效)
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;
}
//if we are inside an action tag, we always need to do an include
Boolean insideActionTag = (Boolean) ObjectUtils.defaultIfNull(request.getAttribute(StrutsStatics.STRUTS_ACTION_TAG_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);
}
}
}
}