Roman C
Roman C

Reputation: 1

How to return a JSON result with JSP in Struts 2

I know that in Struts2 can be used json plugin to return a json type result. A json could also be returned from the stream result like in this answer.

On the Struts2 docs page for Ajax result with JSP, I've found that it's possible to return dispatcher type result with JSP that outputs a JSON.

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

But it's using scriptlets to write JSON to the out. I know that using scriplets in JSP is highly discouraged. But I couldn't find the answer for my problem in this question How can I avoid Java code in JSP files, using JSP 2?. How can I use JSP result to generate a JSON object? Is there a better way to return JSON object from JSP?

Upvotes: 1

Views: 2184

Answers (1)

Andrea Ligios
Andrea Ligios

Reputation: 50281

You can return a JSP through the dispatcher result, then use <s:property /> tag to call an action method that will return the serialized data in the JSP.

You should also express the right contentType for your 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" />

Upvotes: 2

Related Questions