【发布时间】:2022-01-04 01:54:51
【问题描述】:
我需要将一个简单的 json 对象发布到 Struts 2 动作中,你能告诉我我错过了什么吗:
要保存的 Java 对象:
@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;
我使用 alpine.js 但这是一个细节,发送请求调用的脚本是这个:
<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>
发送到动作的json是:
{
"libelleFr":"fr",
"libelleNl":"nl",
"code":"sample"
}
在我的操作文件中,有我从前面调用的方法:
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;
}
根据 struts2 json 插件,如果格式正确,则 json 应该映射到我的对象,但如果我在调试中查看,则字段为空。
你知道我如何才能在我的操作方法中至少看到 json 请求吗?
【问题讨论】:
-
Struts 2 应该不接受来自请求的 json 值,除非这个功能甚至通过插件启用。您应该阅读相应的文档页面以了解如何操作。 This 的答案也有类似的问题,如果您需要通过解决方案解决的问题,您应该先阅读它。
-
嗨@RomanC,感谢您的回复。已经添加了 struts 2 插件。我查看了文档,但没有看到带有注释的示例(例如操作中的操作类)。另外你能确认json插件是否在项目中,我可以只发送与dto结构相同的json数据,插件会自动填充dto字段吗?
-
@RomanC 我成功完成了您在没有拦截器的情况下描述的第二个选项并且它可以工作,但如果我理解使用插件的第一个选项更快
-
该插件由 Struts 2 框架支持,因此您无需编写自己的序列化器和反序列化器。
-
感谢@RomanC。 ,将表单详细信息发送到我的操作中称为“indicateurDictionnaireForm”的 DTO,请求是否正确?我对 JSON 的结构有疑问,是否需要使用指示性词典进行包装?我试过这样,但同样的问题是 dto 没有填充: $.ajax({ type: "POST", async: true, url: "/mesures.indicateurs.ce.save.动作”,数据:{“indicateurDictionnaireForm”:JSON.stringify(this.indicateurDictionnaireForm)},成功:函数(数据){},错误:函数(请求,错误){}});
标签: java json jsp struts2 struts2-jquery