how can i pass value from javascript to a java class in struts2?

心不动则不痛 提交于 2019-11-28 10:47:15

问题


function redirect(id){
alert(id);

document.forms["AddToCart"].submit();
}

This is my javascript. How can i pass the value of 'id' into AddToCart.java. I am using struts2 framework.


回答1:


You can store the value in a hidden field inside your form and so when the form is submitted the value will be sent to Action.

<form name="AddToCart" ... >
...
<input type="hidden" id="myid"/>
.....
</form>

then

function redirect(id){
document.getElementById('myid').value = id;

document.forms["AddToCart"].submit();
}



回答2:


There are many ways to do this and one of the easy way is to pass it as a hidden form field

something like

<s:hidden value="" name="my_ID" id="my_ID"/>

and in you javascript you need to set this hidden input field like

function redirect(id){
alert(id);
document.getElementById("my_ID").value=id;
document.forms["AddToCart"].submit();
}

final step is to create a similar property in your action class with its getter and setters and framework will inject the form value in the respected property

public class MyAction extends ActionSupport{

  private String my_ID  // data type can be as per your requirements
  getter and setters

  public String execute() throws Exception{
     return SUCCESS;
  }

}

this is all you need to do and you will able to get the value inside your action class under my_ID property. I am assuming that AddToCart is your Struts2 Action class else you need to pass the value to your class from your called action.




回答3:


You can not communicate from client(javascript) to server side(java classes) directly. Because javascript is executed by your browser and java classes are executed by your server. So you need to use Ajax request to communicate with java classes.




回答4:


Since you're submitting a form, you can dynamically create a new input in that form containing the id you wish to send and then submit the form.




回答5:


We have to do two things to send a value to action class in struts2

  • send the required value with specific parameter name
  • create variable with the same name mentioned in jsp & create setter,getter methods for that variable.

in action class

public class AddToCart{
private String itemId;

public String getItemId(){
return itemId;
}
public void setItemId(String id){
this.itemId=id;
}
}

this will work.



来源:https://stackoverflow.com/questions/9110221/how-can-i-pass-value-from-javascript-to-a-java-class-in-struts2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!