【问题标题】:How to simply return JSON from a JSP如何简单地从 JSP 返回 JSON
【发布时间】:2012-02-25 20:28:24
【问题描述】:

谁能给我一个例子,说明如何在没有任何外部库的情况下从 jsp 中简单地返回以下 json(Oracle Java 的标准库除外)?

[
   {"label":"item 1", "value":"item 1", "id": 1},
   {"label":"item 2", "value":"item 2", "id": 2},
   {"label":"item 3", "value":"item 1", "id": 3}
];

我试过了

<%-- Set the content type header with the JSP directive --%>
<%@ page contentType="application/json" %>

<%-- Set the content disposition header --%>
<%
   // Returns all employees (active and terminated) as json.
   response.setContentType("application/json");
   response.setHeader("Content-Disposition", "inline");
%>

<%@ page language="java"%>
<%@ page import="java.sql.*"%>
<%@ page import="java.util.*"%>
<%@ page import="java.text.*"%>
<%@ page import="javax.servlet.http.*"%>
<%@ page import="oracle.apps.fnd.common.WebAppsContext"%>
<%@ page import="oracle.apps.fnd.common.WebRequestUtil"%>
<%@ page import="oracle.apps.fnd.common.ResourceStore"%>
<%@ page import="oracle.apps.fnd.common.VersionInfo"%>

[
   {"label":"item 1", "value":"item 1", "id": 1},
   {"label":"item 2", "value":"item 2", "id": 2},
   {"label":"item 3", "value":"item 1", "id": 3}
];

但它似乎不起作用,因为我的 jquery 自动完成功能不适用于它。

这是自动完成代码的一部分:

<html>
<head>
      $(function() {
         var cust_ac = $("#autocomplete input#cust_input").autocomplete({
            source:         "xxpay_json_emp.jsp",
            change:         function (event, ui) { alert(ui.item.id); },
            width:          500,
            max:            3000,
            selectFirst:    false,
            delay:          250,
            minChars:       3,
            matchContains:  1,
            scroll:         false,
            scrollHeight:   200,
            maxItemsToShow: 20
        });
        $('#autocomplete').submit(function() {
           return false;   //  Cancel submit button on form.
        });
      });

      function handleKeyPress(e, form)
      {
         var key = e.keyCode || e.which;

         if (key == 13)
         {
            e.cancelBubble = true;
            e.returnValue = false;
         }
      }

   </script>
</head>
<body class='fdlbod'>
   <div style='padding-left : 20px'>
      <textarea id="holdtext" style="display:none;"></textarea>
      <form id="autocomplete" name="autocomplete">
<%
      out.println("Customer Name:&nbsp;");
      out.println("<input type='text' value='' name='cust_input' id='cust_input' size='80' onkeypress='handleKeyPress(event,this.form)' />");
%>
      </form>
   </div>
</body>
</html>

【问题讨论】:

  • 结果如何?条件“JQuery 不起作用”可能有很多原因。
  • 为什么没有外部库? JSON 库非常易于使用,并且是唯一真正做到这一点的方法。顺便说一下,oracle.apps.fnd 也没有随 Java 一起提供。
  • 我不够聪明,无法弄清楚如何将外部库添加到 oracle java 安装中。

标签: json jsp


【解决方案1】:

从 JSP 文件中,创建 JSON 输出的最简单方法是使用“json-taglib”库。

http://json-taglib.sourceforge.net/

你所要做的就是:

1) 包含库 jar 文件。您可以通过直接下载 jar 文件或添加 pom 依赖项来包含它。 可以在此处找到此标记库的 Maven 存储库; http://maven.nuxeo.org/nexus/content/repositories/public/atg/taglib/json/json-taglib/0.4.1/

2) 在 taglib 定义中添加以下行

3)确保页面输出内容类型为json

4) 然后只使用taglib

这是一个示例代码

<%@page language="java" contentType="application/json;charset=UTF-8" %>

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ taglib prefix="json" uri="http://www.atg.com/taglibs/json" %>

    <json:object>
        <json:property name="section" value="${section.name}"/>
        <json:property name="itemCount" value="${fn:length(items)}"/>
        <json:array name="items" var="cArticle" items="${items}">
            <article:use name="cArticle">
                <json:object>
                <wf-custom-tags:encodeString 
                    inputString="${article.fields.title.value}" 
                    var="encodedTitle"/>
                <json:property name="title" value="${encodedTitle}"/>
                <c:remove var="encodedTitle" scope="page"/>
                </json:object>
            </article:use>
        </json:array>
    </json:object>
    <c:remove var="items" scope="page"/>

【讨论】:

    【解决方案2】:

    这是代码:

    <html>
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
            <title>JSP Page</title>
            <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
            <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js"></script>
        </head>
        <body>
            <h1>Hello World!</h1>
            <label for="autocomplete">Enter some text here</label>
            <input id="autocomplete" name="autocomplete" />
            <script type="text/javascript">
                $(document).ready(function() {
                    $("#autocomplete").autocomplete({
                        source: 'json.jsp',
                        minLength: 2
    
                    });                
                });
            </script>
        </body>
    </html>
    

    这是 JSON:

    [
       {"label":"item 1", "value":"item 1", "id": 1},
       {"label":"item 2", "value":"item 2", "id": 2},
       {"label":"item 3", "value":"item 1", "id": 3}
    ]
    
    <%
       // Returns all employees (active and terminated) as json.
       response.setContentType("application/json");
    %>
    

    【讨论】:

    • 我的 JSP 返回的是字符串而不是 JSON。您的 scriptlet 解决了这个问题。谢谢!
    【解决方案3】:

    您是否尝试自己从网络浏览器调用该页面?输出是否符合您的预期?此外,使用 Firebug 或 Chrome 调试器检查响应标头/有效负载并验证一切是否正确。

    更新我想我成功了 - 去掉那个该死的分号。

    【讨论】:

    • 它甚至似乎都没有调用我的 json(在 Firebug 中看不到任何内容)。这是我的代码:
    • $(function() { var cust_ac = $("#autocomplete input#cust_input").autocomplete({ source: "xxpay_json_emp.jsp", change: function (event, ui) { alert( ui.item.id); }, width: 500, max: 3000, selectFirst: false, delay: 250, minChars: 3, matchContains: 1, scroll: false, scrollHeight: 200, maxItemsToShow: 20 });
    • 更新到最新的jquery和ui,但还是没有:
    • 添加评论时如何使用回车键?看起来它正在返回对萤火虫的响应(在萤火虫中寻找错误的位置)我看到 json 现在回来了,但它没有显示在自动完成上。不确定我的自动完成 CSS 是否正确。
    • 您的选择器对于测试来说似乎过于复杂。只需取一个简单的字段并输入一个 input#id 看看会发生什么。将练习保持在最低限度,直到它起作用为止。
    猜你喜欢
    • 2012-12-09
    • 1970-01-01
    • 2016-01-26
    • 2010-10-19
    • 2011-07-23
    • 2011-11-19
    • 1970-01-01
    • 2011-08-06
    相关资源
    最近更新 更多