struts 2是否接受“POST”方法将数据从javascript发送到Action服务器?

时间:2011-12-16 00:08:18

标签: struts2 client-server http-post

[我试图简化代码以更好地理解问题]当我尝试将数据从Web端客户端发送到Struts 2中的ActionClass时:

jQuery("#bedata").click(function(){ //Function for button "bedata"

 var postData = "SOME DATA TO SEND"

//Sendin data:
$.ajax({
    type: "POST", //Method to send the data. I would need "post" method as better option.
    url: "GuardaFila.action", //Action called to data treatament
    data : {
        jgGridData: postData, //PARAMETER jgGrdData with variable "postData" value
        customData: "someinfo" //Just another parameter called "customData" with more data,
    },


/** START: handlers for request. Not important for this trouble **/
    dataType:"json",
    contentType: "application/json; charset=utf-8",
    success: function(response, textStatus, xhr) {
        alert("success");
     },
    error: function(xhr, textStatus, errorThrown) {
        alert("error");
    }
/** END: handlers for the request. **/
});
});

我想从调用“CargaTabla.action”时调用的ActionClass中自动填充“jgGridData”和“customData”属性。但如果type是POST,则不起作用。 只需更改ajax类型的发送中的POST类型,打开“GET”,它就可以正常工作。对JgGridData和customData的CargaTabla.action ActionClass setters方法的调用已经正确完成。

我的struts.xml重要代码是:

<action name="GuardaFila" method="guardarUsuario" class="org.json.JSONRespuestaTabla">
    <result name="success" type="json" />
</action>

因此,GuardaFila在其方法“guardarUsuario”中的操作在调试程序中被正确调用。 ActionClass(org.json.JSONRespuestaTabla)的简化版本是:

public class JSONRespuestaTabla extends ActionSupport{

String jgGridData = "Old data to be refilled from client";
String customData = "Old data to be refilled from client";

@Override
public String execute() {
    //Some stuff
    return SUCCESS;
}

//Getters and Setter of attributes.

public void setJgGridData(String resultado){
    System.out.append(resultado);
}
public String getJgGridData(){
    return this.jgGridData
}
public String getCustomData() {
    return customData;
}
public void setCustomData(String customData) {
    this.customData = customData;
}

//And the method called and defined in struts.xml (properly called)
public void guardarUsuario(){
   //Some stuff.
   return;
}
嗯,好吧。如果Javascript在GET模式下发送参数,那么SETTERS工作正常,我可以在我自动设置的ActionClass JSONRespuestaTabla上获得“SOME DATA to SEND”,随时可以使用。但是,如果JavaScript以POST模式发送此数据,Struts不会调用setter,并且我无法将数据接收到处理该操作的类中。

怎么样?我不明白为什么会这样。

我正在为struts2使用jquery,json和tiles插件。

1 个答案:

答案 0 :(得分:0)

完成。只需设置数据类型:

contentType: "application/x-www-form-urlencoded; charset=utf-8"

代替:

contentType: "application/json; charset=utf-8"
相关问题