14

Can anyone give me an example of how to return the following json simply from a jsp without any external libraries (except the ones that come standard with 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}
];

I tried

<%-- 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}
];

but it does not seem to work, since my jquery autocomplete does not work with it.

Here's part of the autocomplete code:

<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>
Superdooperhero
  • 7,584
  • 19
  • 83
  • 138

3 Answers3

9

Did you try to invoke the page yourself from a web browser? Is the output what you expected? Also, use Firebug or Chrome Debugger to inspect the response headers/payload and verify that everything is correct.

Update I think I nailed it - take that damned semi-colon away.

Alessandro Santini
  • 1,943
  • 13
  • 17
  • It doesn't even seem to call my json (don't see anything in Firebug). Here's my code: – Superdooperhero Feb 03 '12 at 07:45
  • $(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 }); – Superdooperhero Feb 03 '12 at 07:47
  • Updated to the latest jquery and ui, but still nothing: – Superdooperhero Feb 03 '12 at 08:17
  • How can you use the enter key when adding a comment? Looks like it is returning a response on firebug (was looking on the wrong place in Firebug) I see the json coming back now, but it's not displaying on the autocomplete. Not sure whether my autocomplete css is right. – Superdooperhero Feb 03 '12 at 08:24
  • Your selector seems overly complicated for a test. Just take a simple field and go for an input#id and see what happens. Keep the exercise to the bare minimum until it works. – Alessandro Santini Feb 03 '12 at 09:17
  • I changed my code to use the demo code that comes with jquery (remote-jsonp.html). It connects to geonames.org and works great. I then copy the json from firebug and paste it at the bottom of my json jsp and try to get it to work with that. It does not work. It does not seem to see my json as json. Is there something wrong with my headers? The geonames json also gets wrapped inside a jQuery171030641205356759216_1328259642560(), not sure why. Tried it with and without this, but still does not work. – Superdooperhero Feb 03 '12 at 09:57
  • The example uses jsonp, so I'm not sure whether I need to change my headers from json to jsonp – Superdooperhero Feb 03 '12 at 10:01
  • Try to take the "content-disposition=inline" away. – Alessandro Santini Feb 03 '12 at 11:44
  • Recoded the entire thing to use the demo example that comes with jquery, worked fine with static data; as soon as I switch to the same data with JSON as above then it doesn't work. Also tried to remove content-disposition inline, still does not work. – Superdooperhero Feb 03 '12 at 12:20
  • Taking the semicolon at the end away did the trick, thanks a million. – Superdooperhero Feb 03 '12 at 13:43
6

This is the code:

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

and this is the 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");
%>
Alessandro Santini
  • 1,943
  • 13
  • 17
4

From a JSP file, simplest way to create JSON output is using "json-taglib" library.

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

All you'll have to do is:

1) Include the library jar file. You can either include it by downloading the jar file directly or by adding the pom dependency. Maven repo of this taglib can be found here; http://maven.nuxeo.org/nexus/content/repositories/public/atg/taglib/json/json-taglib/0.4.1/

2) Add following line in the taglib definition

3)Make sure the page output content type is json

4) Then just use the taglib

Here is a sample code

<%@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"/>
Amarjit Datta
  • 251
  • 2
  • 7