Alireza Fattahi
Alireza Fattahi

Reputation: 45475

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

Consider struts 2 webapp on Tomcat 7.0.54.

The web.xml is defined as:

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

This force all Tomcat errors (including 404) be redirected to global-error-page.jsp;

So if I try http://foo.com/bad.jsp or http://foo.com/bad.ext Tomcat redirects me to global-error-page.jsp

However trying http://foo.com/bad.action will still return the 404 error and tomcat can not handle it, is it a way to fix it ?!

Upvotes: 1

Views: 687

Answers (2)

Roman C
Roman C

Reputation: 1

Bad action is handled via implementing UnknownHandler. You can configure it in struts.xml using a tag.

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

The class org.struts.YourUnknownHandler should implement UknownHandler interface to handle the cases:

  • when an action configuration is unknown
  • when a result cannot be found for an action and result code
  • when an action method cannot be found

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.

Read How to implement your unknown handler.

The method handleUnknownAction() should return ActionConfig. This config you should build yourself, you can use ActionConfig.Builder. You can also build result separately, but if you have a global result

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

you can find it in the runtime configuration and add to the newly baked action config.

Upvotes: 1

Andrea Ligios
Andrea Ligios

Reputation: 50203

You can use a default-action-ref to catch all the unmatching actions 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.

Simply map its result to the page you want:

<package...>

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

</package>

Upvotes: 1

Related Questions