我在java中使用spring框架。在我的项目中,我用AJAX调用控制器动作。但是我想让这个动作给我带来2(两个)属性的JSON。状态和结果。在result属性中,我必须在运行时呈现视图。在Spring框架中如何做到这一点。 以下是我的方法:
@RequestMapping(value = "get_new_x", method = RequestMethod.GET)
@ResponseBody
public String GetNewOtpCode(Model model,HttpServletResponse response) {
//code . . . . .
request.setAttribute("xxx", yyy);
request.getSession().setAttribute("zzz", "uyuyt");
String jsonResult = createResultJson(1, renderHtml());
return jsonResult ;
}
public static String createResultJson(String status, String html) {
JSONObject jsonObj = new JSONObject();
jsonObj.append("status", status);
jsonObj.append("result", html);
return jsonObj.toString();
}
结果必须是:{"status": "1", "result":"<h1>Rendered html</h1>"}
我是ASP.NET MVC开发人员。我使用此代码在asp.net mvc中完成了它:
public string RenderRazorViewToString(string viewName, object model)
{
ViewData.Model = model;
using (var sw = new StringWriter())
{
var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
return sw.GetStringBuilder().ToString();
}
}
帮我写renderHtml()方法。感谢...
答案 0 :(得分:0)
你的json应该像{"status": "1", "result":"<h1>Rendered html</h1>"}
。所以先创建一个简单的pojo:
public class Pojo {
private String status;
private String result;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
}
接下来,您应该将控制器方法重组为:
@RequestMapping(value = "get_new_x", method = RequestMethod.GET)
@ResponseBody
public Pojo getNewOtpCode() {
Pojo pojo = new Pojo();
pojo.setStatus("1"); //change status to int in Pojo class if you would like to see a number literal in your json
pojo.setResult(renderHtml());
return pojo;
}
您必须将Jackson添加到您的类路径中。 Spring会自动拾取它。 以下是maven的代表:
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.3</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.3</version>
</dependency>
您可以使用Spring的视图解析here
找到替代解决方案