How to pass a parameter from JSP to Struts 2 action

28,394

Solution 1

This should do :

<s:url id="myurl" action="addToCart">
    <s:param name="id" value="%{#cpu.id}" />
</s:url>
<s:submit  value="addToCart" action="%{myurl}"/>

Solution 2

You need to use form element.

<form action="passId>
    <s:hidden name="id" value="%{#cpu.id}" />
    <s:submit  value="addToCart" action="addToCart" type="submit"/>
</form>

Solution 3

The problem is that you can't parametrize <s:submit> tag with <s:param> tag like in your code using the param tag in the body of the submit tag.

You also don't want to add <hidden> field because you got multiple values submitted to the action. This is because many hidden fields are rendered with the same name. You could use only one field and update its value before submitting a form.

Probably you have used wrong tag to pass a parameter to the action. You can use anchor tag and parametrize it with <s:param> tag.

The second way is to use JavaScript to modify action attribute. In this way you can also use a <button> tag.

Third way is not recommended because it requires to use multiple forms one per each link. In this way you add a parameter to the form action attribute directly.

Below is the code for the options mentioned above.

3-in-1:

<s:form name="myForm13" namespace="/" action="save?message=Hello param 3" theme="simple">
  <br/><s:a cssClass="btn btn-primary" action="test"><s:param name="message">Hello param 1</s:param>&nbsp;&nbsp;&nbsp;Go&nbsp;&nbsp;&nbsp;</s:a>
  <br/><s:a href="#" cssClass="btn btn-warning" onclick="myForm13.action='test?message=Hello param 2';myForm13.submit()">Submit</s:a>
  <br/><s:submit cssClass="btn btn-danger" action="test"/>    
</s:form>

Share:
28,394
Andrei G
Author by

Andrei G

Updated on January 29, 2022

Comments

  • Andrei G
    Andrei G over 2 years

    I have an application and I want to pass item id to the action every time the button for that item is pressed.

    My JSP :

    <s:submit  value="addToCart" action="addToCart" type="submit">
    <s:param name="id" value="%{#cpu.id}" />
    </s:submit>
    

    Action:

    public class ProductsCPU extends BaseAction implements Preparable, SessionAware {
    private static final long serialVersionUID = 2124421844550008773L;
    
    private List colors = new ArrayList<>();
    private List cpus;
    private String id;
    
    public String getId() {
        return id;
    }
    
    public void setId(String id) {
        this.id = id;
    }
    

    When I print id to console, it has the null value. What is the problem?

  • Roman C
    Roman C over 7 years
    Parameters are passed 3in1 but there's another one that you should find it yourself.