1

I need to post a simple json object to a Struts 2 action, could you tell me what I miss with this:

the Java object to save:

@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "id", unique = true, nullable = false)
private Integer id;
@Column(name = "code")
private String code;
@Column(name = "libelle_fr")
private String libelleFr;
@Column(name = "libelle_nl")
private String libelleNl;

I use alpine.js but it's a detail, the script called to send the request is this one:

<script>
    function postForm() {
        return {
            indicateurDictionnaireForm: {
                libelleFr: '',
                libelleNl: '',
                code: ''
            },
            message: '',

            submitData() {
                this.message = ''

                fetch('<%= request.getContextPath() %>/mesures.ce.save.action', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    dataType:"json",
                    body: JSON.stringify(this.indicateurDictionnaireForm)
                })
                    .then(() => {
                        this.message = 'Form sucessfully submitted!'
                    })
                    .catch(() => {
                        this.message = 'Ooops! Something went wrong!'
                    })
            }
        }
    }
</script>

the json sent to the action is:

{
"libelleFr":"fr",
"libelleNl":"nl",
"code":"sample"
}

from my action file there is my method called from the front:

private IndicateurDictionnaire indicateurDictionnaireForm;

// Action to save an indicateurDictionnaireto database
@Action(value = "mesures.indicateurs.ce.save", results = {
            @Result(name = "success", type = "json", params = {"root", "indicateurDictionnaireForm"}),
            @Result(name = "input", type = "tiles", params = {"root", "indicateurDictionnaireForm"}, location = "viewMesureCoutUnitaire")})
    public String save(IndicateurDictionnaire indicateurDictionnaire, String libelleFr, String libelleNl, String code) {
        dictionnaireIndicateurBo.saveIndicateurDictionnaire(indicateurDictionnaire);
        return SUCCESS;
    }

According the struts2 json pluggin, the json should be mapped to my object if it's properly formatted but the fields are empty if I look in debug.

Do you know how I can proceed to at least see the json request in my action method?

Roman C
  • 49,761
  • 33
  • 66
  • 176
Ersch
  • 173
  • 2
  • 15
  • The Struts 2 should *not* accept json values from the request, unless this feature is enabled even via the plugin. You should read the corresponding documentation page to learn how to do it. [This](https://stackoverflow.com/a/16752302/573032) answer has a similar problem and you should read it before if you need a problem solved with the solution. – Roman C Nov 26 '21 at 18:03
  • Hi @RomanC and thanks for your repply. The struts 2 pluggin was already added. I looked the documentation but I don't see the example with anotations (like my action class in the op). Also can you confirm if the json pluggin is in the projet, can I just send the json data with the same structure than the dto and the pluggin will auto populate the dto fields? – Ersch Nov 26 '21 at 20:31
  • @RomanC I did with success the second option that you described without the interceptor and it works but if I understand the first option with the plug-in is faster – Ersch Nov 26 '21 at 20:57
  • The plugin is supported from the Struts 2 framework, so you don't need to write your own serializer and deserializer. – Roman C Nov 26 '21 at 22:25
  • thanks @RomanC. ,Tto send the form detail to the DTO called "indicateurDictionnaireForm" in my op, Does the request is correct? I have a doubt about the structure of the JSON, Do I need to wrap with indicateurDictionnaireForm? I tried like that but same prob the dto is not populated: $.ajax({ type: "POST", async: true, url: "<%= request.getContextPath() %>/mesures.indicateurs.ce.save.action", data: {"indicateurDictionnaireForm": JSON.stringify(this.indicateurDictionnaireForm)}, success: function (data) { }, error: function (request, error) { } }); – Ersch Nov 26 '21 at 22:50

1 Answers1

1

The methods that are mapped to the actions not use any parameters in the method signature. So you need to remove those parameters and add json interceptor to the action config.

This field is used as root object by the json interceptor and should not be null.

IndicateurDictionnaire indicateurDictionnaire;
// getter and setter should be added

@Action(value = "mesures.indicateurs.ce.save", results = {
    @Result(name = "success", type = "json", params = {"root", "indicateurDictionnaire"})
}, interceptorRefs = @InterceptorRef(value = "json", params = {"root", "indicateurDictionnaire"}))
public String save() {       
  dictionnaireIndicateurBo.saveIndicateurDictionnaire(indicateurDictionnaire);
  return SUCCESS;
}
Roman C
  • 49,761
  • 33
  • 66
  • 176
  • 1
    Thanks a lot it works !! I had another issue, my action class implemented the model driven but I found in another answer from you https://stackoverflow.com/questions/26493800/posting-json-from-ajax-to-struts2-action/26757003#26757003 that it cant work so I removed the modelDriven and it works now. Many thanks for your help – Ersch Nov 27 '21 at 09:27