Before writing a JSON.jsp to get custom json data ,lets see how it works.
Sling gives importance to the resource rather than the type of resource.
Sling gives importance to the resource rather than the type of resource.
The above mentioned statement explains what Sling is.Sling gives us the opportunity to render the same data in different types like html,xml and json etc.
Lets go through response from the below requests.
http://localhost:4502/content/geometrixx/en.html
http://localhost:4502/content/geometrixx/en.json
http://localhost:4502/content/geometrixx/en.xml
All the above three urls requests the data at path "/content/geometrixx/en" , where en is node of type page (cq:Page) . But the response what we get differs based on the extension .
More about sling request processing can be found at
http://dev.day.com/docs/en/cq/current/developing/the_basics.html#Sling Request Processing
Now we have a page and we want to customize the json response on the page we need a "json.jsp" on that page component.
Create a new file by name "json.jsp" for the geometrixx page at path "/apps/geometrixx/components/homepage"and write the code paste the code given below.
<%@ page import="org.apache.sling.commons.json.io.*" %>
<%@include file="/libs/foundation/global.jsp" %>
<%
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
JSONWriter writer = new JSONWriter(response.getWriter());
writer.object();
writer.key("Name");
writer.value("English");
writer.key("Code");
writer.value("en");
writer.endObject();
%>
Now we can see our custom JSON response at
http://localhost:4502/content/geometrixx/en/jcr:content.json
Create a new file by name "json.jsp" for the geometrixx page at path "/apps/geometrixx/components/homepage"and write the code paste the code given below.
<%@ page import="org.apache.sling.commons.json.io.*" %>
<%@include file="/libs/foundation/global.jsp" %>
<%
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
JSONWriter writer = new JSONWriter(response.getWriter());
writer.object();
writer.key("Name");
writer.value("English");
writer.key("Code");
writer.value("en");
writer.endObject();
%>
Now we can see our custom JSON response at
http://localhost:4502/content/geometrixx/en/jcr:content.json
what is the url if the json.jsp is inside a component
ReplyDeleteYou can access the json selector on that particular resource within the page. e.g. a/b/c(page)/jcr:content/componentnode.json.jsp .
Delete