Getting json return type and html return in the same action

2.4k views Asked by At

I'll try be as specific as possible.

I have an Action with two methods, one is called via ajax and other one via regular submit.

The point is that can't get the request from the regular submit, I'm getting only the action properties.

public class ClientAction{

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

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

getRequest from saveClient method returns null!!! But, why??? I didn't declare it with @SMDMethod

and here is the 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>

I did all the others declarations. I used to have two separete classes, one for each method, but maintainability wasn't easy with ClientAction and ClientActionJSON.

Any thoughts on how to have both methods, one ajax and the other not, in the same class.

1

There are 1 answers

1
coding_idiot On BEST ANSWER

I'll straight away consider to write a sample :

<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>

now simply create both methods jsonMethod() & htmlMethod() in your ClientAction, one handling json and another html response.

[EDIT]

I read it again and seems like you require only one-action, well then simply consider using a field (request parameter) to decide the return type.

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>

Above I assumed, returntype is a String variable which you sent along with each request specifying what return is expected. You can simply send it hidden in the form-submit and set it in the ajax-request.