2016-03-02 60 views
0

我知道在Struts2中可以使用json插件返回json類型的結果。 A json也可以從stream的結果返回,如this的答案。如何在Struts 2中使用JSP返回JSON結果

在用於Ajax result with JSP的Struts2文檔頁面上,我發現可以返回dispatcher類型的結果和輸出JSON的JSP。

<%@ 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()); 
    } 
%> 

但它的使用小腳本編寫JSON到了。我知道在JSP中使用腳本非常令人沮喪。但我在這個問題How to avoid Java code in JSP files?找不到我的問題的答案。我如何使用JSP結果生成JSON對象?有沒有更好的方法來從JSP返回JSON對象?

+2

這是一個純粹的運動風格,或者是有實際使用 - 它會導致從DISPATCHER結果中使用JSON帶來某種好處,而不是像往常一樣使用JSON或STREAM結果獲得某種好處?所有這些來自哪裏,這是關鍵? –

+0

@AndreaLigios代碼中使用的風格很糟糕,因爲它使用的是scriptlet。順便說一句,如果你取消刪除它,我會接受答案。 –

+0

我沒有在我的代碼中看到scriptlet,有一個''...順便說一句,未刪除。 –

回答

1

您可以通過dispatcher結果返回JSP,然後使用<s:property />標記來調用一個操作方法,該方法將返回JSP中的序列化數據。

你也應該爲你的JSP表達權contentType

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" />