如何在Struts 2中使用JSP返回JSON结果 [英] How to return a JSON result with JSP in Struts 2

查看:130
本文介绍了如何在Struts 2中使用JSP返回JSON结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在Struts2中可以使用json插件返回 json 类型的结果。还可以从<$ href =https://stackoverflow.com中的结果返回 json / a / 17096564/573032>这个答案。

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.

使用JSP的Ajax结果,我发现可以返回调度程序使用输出JSON的JSP输出结果。

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


但是它使用scriptlet将JSON写入out。我知道在JSP中使用scriplet非常气馁。但是我在如何避免JSP文件中的Java代码?问题中找不到我的问题的答案。如何使用JSP结果生成JSON对象?有没有更好的方法从JSP返回JSON对象?

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 to avoid Java code in JSP files?. How can I use JSP result to generate a JSON object? Is there a better way to return JSON object from JSP?

推荐答案

您可以通过返回JSP调度程序结果,然后使用< s:property /> 标记来调用将返回JSP中的序列化数据的操作方法。

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.

您还应该为您的JSP表达正确的 contentType

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

这篇关于如何在Struts 2中使用JSP返回JSON结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆