简体   繁体   中英

Defining a Default Method within an Action for Struts 1

Is there a way in struts 1 to define a default method within an action? Ie if if I had some action called "register" (with various methods associated with that method), could I then default to a certian method if the passed method is unknown?

To illustrate, say I have localhost:8000/register.do?method=processRegistration where processRegistration is a method within the register action. Now, if I were to instead navigate to a method that does not exist (ie localhost:8000/register.do?method=foobar) it would print a stacktrace error to the browser, giving a "NoSuchMethodException." My thinking would be to try and handle this case would be to define a default method that would be run in cases that trigger the exception. I'm not sure if my line of thinking is correct, but any help would be appreciated. Thanks!

Perhaps you need to create an error page to hide the stack trace? If yes, that's not related to struts. For example, define a custom error page in web.xml.

If you really want to do this I'm guessing you have something like this:

public class RegisterAction extends DispatchAction {

    public ActionForward processRegistrion(...) {
       ...
    }
}

DispatchAction throws the exception so extend DispatchAction and catch the exception, and send to a default method:

public abstract class MyDispatchAction extends DispatchAction {

    public ActionForward execute(...) {
        try {
            return super.execute(...);
        } catch (Exception e) {
            return defaultMethod(...);        
       }

    public abstract ActionForward defaultMethod(...);

}

and your class now extends 'MyDispacthAction and implements defaultMethod`:

public class RegisterAction extends MyDispatchAction {

    public ActionForward processRegistrion(...) {
       ...
    }

    public ActionForward defaultMethod(...) {
       ...
    }

}

But what would defaultMethod actually do?

If you are looking for another solution, you can override the unspecified method of DispatchAction.

public final class MyAction extends DispatchAction {

    @Override
    public ActionForward unspecified(final ActionMapping mapping, final ActionForm form, final HttpServletRequest request,
        final HttpServletResponse response) throws Exception {
    }
}

In my case, I have overrided the getParameter method too...in order to manage the case between parameter/method name (force a lowercase).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM