获取json返回类型和html返回相同的操作

时间:2013-08-23 21:06:13

标签: json struts2 struts2-json-plugin

我会尝试尽可能具体。

我有两个方法的Action,一个是通过ajax调用的,另一个是通过常规提交。

关键是无法从常规提交中获取请求,我只获取操作属性。

public class ClientAction{

    @SMDMethod
    public Map<String, Object> findClient(String myParam){
    ...
    }

    public String saveClient(){            
        Map<String, String[]> parameterMap = this.getRequest().getParameterMap();
    }
}

来自saveClient方法的getRequest返回null!但为什么???我没有用@SMDMethod声明它

这是struts.xml

<action name="client" class="myCompany.ClientAction">
        <interceptor-ref name="customJSON"><param name="enableSMD">true</param></interceptor-ref>
        <result type="json"><param name="enableSMD">true</param></result>
</action>

我做了所有其他声明。我曾经有两个separete类,每个方法一个,但ClientAction和ClientActionJSON的可维护性并不容易。

关于如何在同一个班级中同时拥有两个方法,一个是ajax而另一个没有的任何想法。

1 个答案:

答案 0 :(得分:3)

我会马上考虑写一个样本:

<action name="xclient" class="myCompany.ClientAction" method="jsonMethod">
    <result type="json"></result>
</action>
<action name="yclient" class="myCompany.ClientAction" method="htmlMethod">
    <result type="dispatcher">/pages/y.jsp</result>
</action>

现在只需创建两个方法jsonMethod()&amp;您的ClientAction中的htmlMethod(),一个处理json和另一个html响应。

[编辑]

我再次阅读它,看起来你只需要一个动作,然后只需考虑使用一个字段(请求参数)来决定返回类型。

public String execute(){
    //..Other code
    if(returntype.equals("json")){
        return "jsonresult";
    }
    else{
        return "htmlresult";
    }
}

<action name="client" class="myCompany.ClientAction" method="jsonMethod">
    <result name="jsonresult" type="json"></result>
    <result name="htmlresult" type="dispatcher">/pages/y.jsp</result>
</action>

上面我假设,returntype是一个String变量,您随每个请求一起发送,指定预期的返回值。您只需将其隐藏在表单提交中,然后将其设置在ajax-request中即可。

相关问题