Ajax With JSP Developed in NetBeans
Ajax With JSP Developed in NetBeans
Apache Tomcat and NetBeans IDE 7.0. You will build our AJAX server by using jsp technology and the work will be done in NetBeans IDE. Step 1: Startup NetBeans. Select File->New Project
Step2: Select Web and Web Application, then Next. In the new dialog box, name your project and choose a location for it. Press finish when youre finished with it. You will see a default page index.jsp and the directory structure like this where you can place
You can run this default page by clicking Run->Run Main Project. It takes few seconds to launch the build-in Java server. Also, the new jsp file needs to be compiled. After all, a new browser would be open automatically with a simple page.
Step 3: Copy the following code to the default page index.jsp <HTML> <head> <script type="text/javascript"> var req; function ajaxCall() { var poststr = "username=" + encodeURI(document.frmtest.content.value); var url = "ajax.jsp"; if (window.XMLHttpRequest) { req = new XMLHttpRequest(); } else if (window.ActiveXObject) { req } req.open("POST", url, true); req.onreadystatechange = callback; req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); req.setRequestHeader("Content-length", = new ActiveXObject("Microsoft.XMLHTTP");
poststr.length); req.setRequestHeader("Connection", "close"); req.send(poststr); } function callback() { if (req.readyState == 4) { if (req.status == 200) { // update the HTML DOM based on whether or not message is valid parseMessage(); } } } function parseMessage() { var message = req.responseText; setMessage(message); } function setMessage(message) { mdiv = document.getElementById("Message"); mdiv.innerHTML } = "<div style=\"color:green\">"+message+"</ div>";
</script> </head> <body> <form action="" name="frmtest"> <textarea </form> <div id="Message"></div> </body> </html> Create a new file named ajax.jsp in the same folder, and copy the following code to it: <% String content = request.getParameter("username"); content = "Hello! " + content; response.setContentType("text/html"); response.setHeader("Cache-Control", "no-cache"); response.getWriter().write(content); %> name="content" rows="3" cols="40" onkeyup="javascript:ajaxCall();"></textarea>
Step 4: You launch the server Run->Run Main Project. In the new default page you can see a text area.
If you enter some name in the text area, the page responses you automatically and seamlessly without a push button invocation.
You can find in this example that Ajax client works in an asynchronous mode without loss of operation context rather than in the click, wait, and fresh request/response communication user interaction mode.
The Ajax client only refreshes the updated portion of the page partially and gets the instant feedback for client user s activities.