开发者

How to return an 404 error when I use Struts 2 wildcard configuration?

I am building a website using struts 2 . Here is a clip of my "struts.xml":

<action name="*" class="com.domain.actions.UserAction" method="{1}">        
    <result name="myresult">/Pages/myresult.jsp</result>
    <!-- there are many other resu开发者_开发百科lts -->
</action>

Now, I got a problem.

When I visit an action I didn't design, such as "aaabbb", the server will return a 500 error.

because of the wildcard configuration, struts 2 will try to call the "aaabbb" method of class "com.domain.actions.UserAction", but the "aaabbb" method not exsits.

But, by logically, return a 404 error is better.

How can I return a 404 error in these situation and use wildcard configuration at the same time ?


I'm no Struts2 expert, but you might try this:

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

Then have an "error" action that returns the 404.


In Struts 2 if the method attribute value does not exist, the execute() method is invoked.

This means that you can return a custom result value in your execute method like so:

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

Then in your struts.xml mapping you can create a result type that is of the type "httpheader" like so:

<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>

This will invoke a 404 on the header. This will take the user to whatever error mapping you may have in your web.xml like so:

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


Another idea that will return a 404. (That's the only one that worked in my case)

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜