Struts2 - Going to an Invalid URL does not redirec

2019-08-29 11:46发布

问题:

This question already has an answer here:

  • How to define a global page when requested page or method is not found? 2 answers

I do not know what configuration changes I may have done to cause this, but for some reason, going to an invalid URL which maps to no struts2 action, only gives a blank page. It does not redirect to the Mapped 404 page, and it does not even display the "There is no Action mapped for namespace [/] and action name []" like it used to. I am trying to get my 404 page working, but I have no clue what is going on here. In my web.xml I have:

<filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>REQUEST</dispatcher>
    <dispatcher>FORWARD</dispatcher>
    <dispatcher>ERROR</dispatcher>
</filter-mapping>

<error-page>
    <error-code>404</error-code>
    <location>/jsp/error/404.jsp</location>
</error-page>

Have any idea as to why blank pages are being served with invalid URL's and actions? I appreciate the help

回答1:

Finally - After deep searching about this issue, I'll find a great solution to how get this works as probably!

1st: you need to add the com.opensymphony.xwork2.UnknownHandler bean in your struts.xml:

<bean type="com.opensymphony.xwork2.UnknownHandler" name="handler" class="com.path.to.your.InvalidRequests"/>


2nd: setup an action to refer into the page not found behavior.

<action name="pageNotFound" class="com.path.to.your.PageNotFound" method="execute">
   <result name="success">/jsps/404.jsp</result>
</action>


3rd: in your custom handler you need to define your com.opensymphony.xwork2.config.entities.ActionConfig and check if the action is already exists in your action configuration lists

public class InvalidRequests implements UnknownHandler {
@Override
public ActionConfig handleUnknownAction(String namespace, String actionName) throws XWorkException {
    ConfigurationManager configurationManager = Dispatcher.getInstance().getConfigurationManager();
    RuntimeConfiguration runtimeConfiguration = configurationManager.getConfiguration().getRuntimeConfiguration();
    ActionConfig actionConfig = runtimeConfiguration.getActionConfig(namespace, actionName);
    if(actionConfig == null) { // invalid url request, and this need to be handled
        actionConfig = runtimeConfiguration.getActionConfig("", "pageNotFound");
    }
    return actionConfig;
}
// ... also you need to implements handleUnknownResult, handleUnknownActionMethod
}


Keep in mind you need to override the both of methods handleUnknownResult and handleUnknownActionMethod and the both of methods return null.