如何在Struts 2 Action类中接收json请求数据,这是由jquery的getJSON()发送的?

时间:2017-01-12 08:07:57

标签: java jquery json struts2

我正在创建一个基于Struts 2的Web应用程序,我想在其中向jQuery getJSON()发送包含JSON数据的请求到Action类。这种情况正在发生。

但是我的Action类无法接收JSON数据。任何努力都会提前得到很多赞赏。

$.getJSON("getPaycells", {
    level: $(this).val(), 
    ajax: 'true'
}, function(j){});
struts.xml中的

<action>元素:

<action name="getPaycells" class="pkg.ActionClassName">    
    <exception-mapping exception="java.lang.Exception" result="ERROR" />
    <interceptor-ref name="json">
        <param name="contentType">application/json</param>
    </interceptor-ref>
    <result type="json"/>
</action>

动作类:

public class PayMatrix extends ActionSupport
{
    private Map data = new HashMap();

    public Map getData()
    {
        return data;
    }

    public void setData(Map data)
    {
        this.data = data;
    }

    public String execute()
    {
        System.out.print("MYDATA-"+data);
        return null;
    }
}

1 个答案:

答案 0 :(得分:2)

http://tech.learnerandtutor.com/send-json-object-to-struts-2-action-by-jquery-ajax/

上有一篇非常好的文章

尝试将enableSMD设为true

<interceptor-ref name="json">
  <param name="enableSMD">true</param>
</interceptor-ref>

还尝试使用以下内容:

$.ajax({
    url: "writeJSON.action",
    data: data1,
    dataType: 'json',
    contentType: 'application/json',
    type: 'POST',
    async: true,
    success: function (res) {
        ....
    }
});

如果json interceptor没有特定属性,org.apache.struts2.json.JSONInterceptor会弃置您的请求。

我自己通过在intercept //download your audio file NSString *urlString = @"http://www.smartivr.in/sounds/voicemail/download/f77245d9-e7ee-4424-850c-6a45022d0a54_1.mp3"; NSURL *url = [NSURL fileURLWithPath:urlString]; NSData *soundData = [NSData dataWithContentsOfURL:url]; NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"sound.caf"]; [soundData writeToFile:filePath atomically:YES]; // get the file from directory NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES); NSString *documentsDirectory = [pathArray objectAtIndex:0]; NSString *soundPath = [documentsDirectory stringByAppendingPathComponent:@"sound.caf"]; NSURL *soundUrl; if ([[NSFileManager defaultManager] fileExistsAtPath:soundPath]) { soundUrl = [NSURL fileURLWithPath:soundPath isDirectory:NO]; } // play audio file audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundUrl error:nil]; [audioPlayer prepareToPlay]; [audioPlayer play]; 方法设置一些断点来解决我的问题,这将有助于我为什么拦截器不适用于我的请求。