| GET function doRequestUsingGET() { createXMLHttpRequest(); var queryString = " GetAndPostExample? " ; queryString = queryString + createQueryString()+ " &timeStamp= " + new Date().getTime(); xmlHttp.onreadystatechange = handleStateChange; xmlHttp.open( " GET " , queryString, true ); xmlHttp.send( null ); } POST function doRequestUsingPOST() { createXMLHttpRequest(); var url = " GetAndPostExample?timeStamp= " + new Date().getTime(); var queryString = createQueryString(); xmlHttp.open( " POST " , url, true ); xmlHttp.onreadystatechange = handleStateChange; xmlHttp.setRequestHeader( " Content-Type " , " application/x-www-form-urlencoded " ); xmlHttp.send(queryString); } |
| import java.io. * ; import java.net. * ; import javax.servlet. * ; import javax.servlet.http. * ; public class GetAndPostExample extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response, String method) throws ServletException, IOException { // Set content type of the response to text/xml response.setContentType( " text/xml " ); // Get the user's input String firstName = request.getParameter( " firstName " ); String middleName = request.getParameter( " middleName " ); String birthday = request.getParameter( " birthday " ); // Create the response text String responseText = " Hello " + firstName + " " + middleName + " . Your birthday is " + birthday + " . " + " [Method: " + method + " ] " ; // Write the response back to the browser PrintWriter out = response.getWriter(); out.println(responseText); // Close the writer out.close(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Process the request in method processRequest processRequest(request, response, " GET " ); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Process the request in method processRequest processRequest(request, response, " POST " ); } } |
| function createXML() { var xml = " <pets> " ; var options = document.getElementById( " petTypes " ).childNodes; var option = null ; for ( var i = 0 ; i < options.length; i ++ ) { option = options[i]; if (option.selected) { xml = xml + " <type> " + option.value + " <\/type> " ; } } xml = xml + " <\/pets> " ; return xml; } function sendPetTypes() { createXMLHttpRequest(); var xml = createXML(); var url = " PostingXMLExample?timeStamp= " + new Date().getTime(); xmlHttp.open( " POST " , url, true ); xmlHttp.onreadystatechange = handleStateChange; xmlHttp.setRequestHeader( " Content-Type " , " application/x-www-form-urlencoded " ); xmlHttp.send(xml); } |