Struts 2 returns 404 不是由 tomcat 错误页面触发

Struts 2 returns 404 which is not triggered by tomcat error-page

考虑在 Tomcat 7.0.54 上使用 struts 2 webapp。

web.xml定义为:

<error-page>
    <location>/WEB-INF/content/global-error-page.jsp</location>
</error-page>

这强制 所有 Tomcat 错误(包括 404)被重定向到 global-error-page.jsp;

所以如果我尝试 http://foo.com/bad.jsphttp://foo.com/bad.ext Tomcat 将我重定向到 global-error-page.jsp

但是尝试 http://foo.com/bad.action 仍然会 return 404 错误并且 tomcat 无法处理它,是否有解决方法?!

您可以使用 default-action-ref 来捕获所有不匹配的操作 as described in the docs:

Usually, if an action is requested, and the framework can't map the request to an action name, the result will be the usual "404 - Page not found" error. But, if you would prefer that an omnibus action handle any unmatched requests, you can specify a default action. If no other action matches, the default action is used instead.

There are no special requirements for the default action. Each package can have its own default action, but there should only be one default action per namespace.

只需将其结果映射到您想要的页面:

<package...>

    <default-action-ref name="index" />
    
    <action name="index">
        <result>/WEB-INF/content/global-error-page.jsp</result>
    </action>

</package>

通过实施 UnknownHandler 处理不良操作。您可以使用标签在 struts.xml 中配置它。

<bean type="com.opensymphony.xwork2.UnknownHandler" name="myhandler" class="org.struts.YourUnknownHandler"/>

class org.struts.YourUnknownHandler 应该实现 UknownHandler 接口来处理以下情况:

  • 当操作配置未知时
  • 当找不到操作和结果代码的结果时
  • 当找不到操作方法时

Struts 2 can be also configured to handle unknown action or result, even without default-action-ref tag it provides a configuration to process such requests. Generally you can use unknown-handler-stack tag by the Struts2 xml configuration and reference handlers. You should check that what com.opensymphony.xwork2.UnknownHandler is provided. If you are using a convention plugin it supplies by default convention unknown handler, which could probably handle your action or result.

阅读

方法 handleUnknownAction() 应该 return ActionConfig。这个配置你应该自己构建,你可以使用 ActionConfig.Builder。您也可以单独构建结果,但如果您有全局结果

<global-results>
  <result name="error">/WEB-INF/content/global-error-page.jsp</result>
</global-results>

您可以在运行时配置中找到它并添加到新烘焙的动作配置中。