我知道在Struts2中可以使用json插件来返回json
类型的结果。还可以从 stream
结果返回 json
,如 this 中所示。回答。
在 Struts2 文档页面上 Ajax result with JSP ,我发现可以使用输出 JSON 的 JSP 返回 dispatcher
类型结果。
<%@ page import="java.util.Iterator, java.util.List, com.esolaria.dojoex.Book, com.esolaria.dojoex.BookManager" %> <% String bookIdStr = request.getParameter("bookId"); int bookId = (bookIdStr == null || "".equals(bookIdStr.trim())) ? 0 : Integer.parseInt(bookIdStr); Book book = BookManager.getBook(bookId); if (book != null) { out.println(book.toJSONString()); System.out.println("itis: " + book.toJSONString()); } %>
但它使用 scriptlet 将 JSON 写入输出。我知道强烈建议不要在 JSP 中使用 scriplet。但我在这个问题How can I avoid Java code in JSP files, using JSP 2?中找不到我的问题的答案。如何使用 JSP 结果生成 JSON 对象?有没有更好的方法从 JSP 返回 JSON 对象?
最佳答案
可以通过dispatcher
返回JSP结果,然后使用 <s:property />
标记来调用将在 JSP 中返回序列化数据的操作方法。
您还应该表达正确的contentType
对于您的 JSP:
public class DispatcherJsonAction extends ActionSupport {
private Book book;
@Action("dispatcherJson")
@Result(name = ActionSupport.SUCCESS, location = "page.jsp")
public String execute(){
book = loadBookSomeHow();
return SUCCESS;
}
public String getJsonBook(){
Gson gson = new Gson();
try {
return gson.toJson(book);
} catch (Exception e){
return gson.toJson(e.getMessage());
}
}
}
page.jsp:
<%@page language="java" contentType="application/json; charset=UTF-8" pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags" %>
<s:property value="jsonBook" />
关于java - 如何在 Struts 2 中使用 JSP 返回 JSON 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35753928/