============ Internet Technologies ============================= ================================================================ This is a "hello world" example using JSON and AJAX. A Javascript JSON parsing libary is in Netbeans under the Web Pages folder. This file is named "json_sans_eval.js". A very small Javascript file is also under the Web Pages folder and is shown next: Its name is "GetJSON.js". ================================================================ function getSomeJSON() { var xhr; if(window.XMLHttpRequest) xhr = new XMLHttpRequest(); else xhr = ActiveXObject("Microsoft.XMLHTTP"); xhr.onreadystatechange = function() { // handle callback by calling handleJSON if(xhr.readyState == 4) { var result = xhr.responseText; handleJSON(result); } } xhr.open("GET", "JSONHelloServlet",true); xhr.send(null); } function handleJSON(someJSONFromServer) { // Use library to parse the string back from server var myJsonObj = jsonParse(someJSONFromServer); // Find the value of the Hello identifier var returnedValue = myJsonObj.Hello; // Place the returnedValue in the DOM. // The id coolLocation is used to find the location. var contents = document.getElementById("coolLocation"); // Erase current value contents.innerHTML = ""; // Add the value of the JSON name, value pair. contents.appendChild(document.createTextNode(returnedValue)); } ================================================================= Shown next is the index.jsp page. ================================================================= <%-- Document : index Created on : May 30, 2013, 10:56:01 PM Author : mm6 --%> <%@page contentType="text/html" pageEncoding="UTF-8"%> Hello JSON

Hello JSON

JSON goes here.

====================================================================== And finally, here is the servlet. Note that the servlet may be called with a full page refresh or with an XHR request. ====================================================================== import java.io.IOException; import java.io.PrintWriter; import java.util.Iterator; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author Mike McCarthy * This is a simple servlet that returns a JSON string to the browser. * */ @WebServlet(name = "JSONHelloServlet", urlPatterns = {"/JSONHelloServlet"}) public class JSONHelloServlet extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String coolJSONString = ""; response.setContentType("application/json"); StringBuffer json = new StringBuffer(); // A JSON object {"Hello":"World JSON"} json.append("{\"Hello\":\"Hello JSON\"}"); coolJSONString = json.toString(); response.getWriter().write(coolJSONString); } }