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 different, 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:
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.
Redirecting the user after a successful post completely nullifies this point. Look at the “Redirect After Post” or “Post/Redirect/Get” pattern).