开发者

Struts 2 Action Methods

开发者 https://www.devze.com 2023-01-07 05:18 出处:网络
Time for yet another stupid question, adding to a long line of them. I\'m a newbie with Struts 2, having spent years using old 1.X. Struts 2 actions can be roughly开发者_如何学JAVA equivalent to Stru

Time for yet another stupid question, adding to a long line of them.

I'm a newbie with Struts 2, having spent years using old 1.X. Struts 2 actions can be roughly开发者_如何学JAVA equivalent to Struts 1 DispatchActions, simply by adding methods (and defining them in struts.xml).

So, suppose I have this method:

public String create() throws Exception {
    // insert create logic here
}

What I want is to have create() do double duty. If create() is called without being passed any parameters, it returns INPUT (and displays the JSP form page), otherwise it processes the form data and returns SUCCESS (and displays a default page).

The only way I have now is to check and see if any values are in the request, which seems silly to me. If I could say "if I call this via HTTP GET show the form, if I call this via HTTP POST, process then redirect to the default".

Like I said, I'm probably being pretty dumb here, but any help would be appreciated.


What you are looking for is to use the same action to show a form and then (after submit) process the form.

public class MyAction {
    @SkipValidation
    public String execute() throws Exception {
        return INPUT; // shows the form
    }

    public void validate() {
        // do your validations here...
    }

    public String submit() throws Exception {
        // process the form
        // redirect somewhere
    }
}

If your action is mapped as "myaction", then your form should submit to "myaction!submit" (that's Dynamic Method Invocation, which invokes your submit() method).

You'll need to create a custom interceptor if you want to enforce that the execute and submit methods are invoked only by HTTP GET and POST methods (respectively).

0

精彩评论

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