How to redirect user to different pages based on the submit button in Struts 2

Jack picture Jack · Mar 28, 2014 · Viewed 11.5k times · Source

First, please note I know the following code is not in JavaScript or jQuery but I just added them as tags of this question in hope of finding a solution for it using Javascript or jQuery.

I have a form with three submit buttons. The problem is that, when I submit the form with either of the buttons the result page will be sent to the same address. I need it to be in a different address.

Purpose:

The code is supposed to show a list of items for a specific category in a page called view. User selects few items and submit the form. Server needs to show the details of the selected items in a page called update (separate address with view page). Then user is able to edit the details of items and submit the form to update the details of those items.

Requirement:

lets say address is

myexample.com/Product/view      //shows view page

after clicking on edit, it should redirect to following address.

myexample.com/Product/update     //shows update page ( show details of selected products)

Potential Solution:

Based on Roman C's answer, after receiving the request, I pass the products list to the other action to show update page, but it shows it as following on the address; therefore, update page does not recognize products parameter as a list.

...products=[1%2C+2]&id=1

Java:

List <Integer> products = new ArrayList();
   

Struts redirect:

   <result name="updateProducts" type="redirectAction">
            <param name="actionName">update</param>
            <param name="namespace">/products/Update</param>
            <param name="products">${products}</param>
            <param name="id">${id}</param>
   </result>

Even if I manually send the following request, the action class does not recognize products parameter as a list. It shows it's size is Zero.

 ...products=[1,2]&id=1

Answer

Roman C picture Roman C · Mar 31, 2014

You should add a redirectAction result to the action config of the action that processes a submit request. In your case it has an edit name, that is confusing, should name like save or update because when you name it edit many programmers think like you are making a request to populate some textfields. But it's not true, your edit action doesn't populate, rather than submits to the server. After submit you should follow the Post-Redirect-Get pattern and return a redirectAction or redirect result to the other action or URL not nessesary to view or edit actions if you don't want to stay on the page after redirecting. Remove the edit action config as it has covered by the wildcard mapping. Add the save button

<s:submit id="saveBtn" action="save" value="Save"/>

add and return redirect action result from the save action

<action name="save" method="save" class="myexample.Product">
  <result type="redirectAction" name="list" />
</action>