【问题标题】:How to return an 404 error when I use Struts 2 wildcard configuration?使用 Struts 2 通配符配置时如何返回 404 错误?
【发布时间】:2011-08-02 07:16:41
【问题描述】:

我正在使用 struts 2 构建网站。 这是我的“struts.xml”的剪辑:

<action name="*" class="com.domain.actions.UserAction" method="{1}">        
    <result name="myresult">/Pages/myresult.jsp</result>
    <!-- there are many other results -->
</action>

现在,我遇到了一个问题。
当我访问一个不是我设计的动作时,例如“aaabbb”,服务器会返回一个 500 错误。
由于通配符配置,struts 2 会尝试调用“com.domain.actions.UserAction”类的“aaabbb”方法,但“aaabbb”方法不存在。
但是,从逻辑上讲,返回 404 错误更好。
如何在这些情况下返回 404 错误并同时使用通配符配置?

【问题讨论】:

    标签: java jsp jakarta-ee struts2


    【解决方案1】:

    我不是 Struts2 专家,但你可以试试这个:

    <global-exception-mappings>
      <exception-mapping exception="java.lang.Exception" result="error"/>
    </global-exception-mappings>
    

    然后有一个返回 404 的“错误”操作。

    【讨论】:

      【解决方案2】:

      在 Struts 2 中,如果方法属性值不存在,则调用 execute() 方法。

      这意味着您可以在执行方法中返回自定义结果值,如下所示:

      public String execute() throws Exception {
          // if the method * does not exist, we will return a "404ERROR" result
          return "404ERROR";
      }
      

      然后在您的 struts.xml 映射中,您可以创建一个类型为“httpheader”的结果类型,如下所示:

      <action name="*" class="com.domain.actions.UserAction" method="{1}">        
          <result name="myresult">/Pages/myresult.jsp</result>
          <!-- there are many other results -->
          <result name="404ERROR" type="httpheader">
              <param name="error">404</param>
              <param name="errorMessage">This is a 404 error. Method does not exist</param>
          </result>
      </action>
      

      这将在标头上调用 404。这会将用户带到您的 web.xml 中可能存在的任何错误映射,如下所示:

      <error-page>
          <error-code>404</error-code>
          <location>/error404.html</location>
      </error-page>
      

      【讨论】:

        【解决方案3】:

        另一个会返回 404 的想法。(在我的情况下,这是唯一可行的)

        public String execute() {             
            ServletActionContext.getResponse().setStatus(HttpServletResponse.SC_NOT_FOUND);
           return SUCCESS;
        }
        

        【讨论】:

          猜你喜欢
          • 2017-07-25
          • 1970-01-01
          • 2018-06-07
          • 1970-01-01
          • 1970-01-01
          • 2016-06-03
          • 1970-01-01
          • 1970-01-01
          • 2014-02-13
          相关资源
          最近更新 更多