我正在搜索如何解释 Spring Portlet MVC 中 @ResourceMapping 中的 JSON 参数。当我添加@RequestBody时,我收到消息:不支持@RequestBody...真的卡在这个上了。
我有这个:
查看侧面:
<portlet:resourceURL var="getTest" id="ajaxTest" ></portlet:resourceURL>
<p>
<button onClick="executeAjaxTest();">Klik mij!</button>
<button onClick="$('#ajaxResponse').html('');">Klik mij!</button>
</p>
<p>
<h3>Hieronder het antwoord:</h3>
<h4 id="ajaxResponse"></h4>
</p>
<script>
function executeAjaxTest() {
var jsonObj = {
user: "Korneel",
password: "testpassword",
type: {
testParam: "test",
}
}
console.debug(JSON.stringify(jsonObj));
$.ajax({
dataType: "json",
contentType:"application/json",
mimeType: 'application/json',
url:"<%=getTest%>",
data:JSON.stringify(jsonObj),
success : function(data) {
$("#ajaxResponse").html(data['testString']);
}
});
}
</script>
控制器端:
@ResourceMapping(value="ajaxTest")
@ResponseBody
public void ajaxTestMethod(ResourceRequest request, ResourceResponse response) throws IOException, ParseException {
LOGGER.debug("ajax method");
JSONObject json = JSONFactoryUtil.createJSONObject();
json.put("testString", "Ik ben succesvol verstuurd geweest!");
response.getWriter().write(json.toString());
}
如何使用 spring magic 自动将此 JSON 数据映射到我自己的模型?
注意:这是 Spring Portlet MVC,而不是常规的 Spring MVC。
Spring MVC portlet 框架不支持开箱即用的 @ResponseBody 注释,但您可以自己实现 @ResponseBody 处理。
我们通过实现自定义视图类型、模型和视图解析器来实现这一点。
- 实现自定义模型和视图解析器(ModelAndViewResolver),比方说 JsonModelAndViewResolver。
- 在resolveModelAndView方法中,检查控制器方法是否具有@ResponseBody注释(或更具体的条件来识别JSON输出 - 例如注释+所需支持的mime类型)。
- 如果是,请返回您的自定义 View 实现 - 假设 SingleObjectJson 视图(扩展 AbstractView)。
- 将要序列化的对象传递给视图实例。
- 视图会将对象序列化为 JSON 格式并将其写入响应(通过在 renderMergedOutputModel 方法中使用 Jackson、Gson 或其他框架)。
- 将新解析器注册为 AnnotationMethodHandlerAdapter.customModelAndViewResolvers。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)