Control action method by GET or POST in struts2
I'm new to Struts2, coming from a PHP background, where I'd often have the same file handling GET and POST requests, and processing a form if the request is a POST request.
I currently have the following in struts.xml:
<action name="ProcessData" class="ProcessDataAction">
<result name="*">processdata.jsp</result>
</action>
<action name="ProcessDataUpload" class="ProcessDataAction" method="upload">
<result name="*">processsdata.jsp</result>
</action>
Which works fine, but it bothers me that the URL that handles POST is differen开发者_运维问答t, since now if the user reloads the page, they get an error rather than simply seeing the contents of the GET page.
So my question is, is there any way to tell struts2 to call one method if it's a GET request, and another method if it's a POST request?
Struts2 doesn't offer what you described out of the box. If you want to enforce that a particular action method is invokable only by certain HTTP methods, then you'd need to create a custom interceptor and probably a few custom annotations.
If you just want the same action to handle displaying the form and processing it, then you can do the following:
public class MyAction {
public String execute() {
return INPUT;
}
public void validate() {
// perform any form validation needed
}
public String submit() {
// process the form and then redirect
}
}
In your form, you would submit to ProcessData!submit. The ! separates the action from the action method name. It provides what you have already, but you don't need to explicitly map each method in the struts.xml.
But it bothers me that the URL that handles POST is different, since now if the user reloads the page, they get an error rather than simply seeing the contents of the GET page.
Redirecting the user after a successful post completely nullifies this point. Look at the "Redirect After Post" or "Post/Redirect/Get" pattern).
Not by default, no. IMO the cleanest solution is to tweak the method name via an interceptor that looks at the request type. For example, I had a simple one that looked for executeGet and executePost methods.
Whether or not it's a great idea... different issue.
精彩评论