Friday, July 14, 2017

Simple JSP Ajax Tutorial

In this blog post, a simple JSP Ajax sample for adding two numbers.  Ajax is a method for returning a result without reloading the HTML page using JavaScript, DOM, XMLHttpRequest and CSS technologies.

ajaxsample.html

<html>
<head>
<script type="text/javascript">
var request;
function addnum() {
var num1 = document.addform.num1.value;
var num2 = document.addform.num2.value;
var url = "sum.jsp?num1=" + num1 + "&num2=" + num2;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
} else if (window.ActiveXObject) {
request = new ActiveXObject("Microsoft.XMLHTTP");
}

try {
request.onreadystatechange = getsum;
request.open("GET", url, true);
request.send();
} catch (e) {
alert("Unable to process");
}
}

function getsum() {
if (request.readyState == 4) {
var sum = request.responseText;
document.getElementById("sumvalue").innerHTML = sum;
}
}
</script>
</head>
<body>
<h1>JSP Ajax Simple Example</h1>
<form name="addform">
<input type="text" name="num1"> + <input type="text"
name="num2"> <input type="button" value="Add"
onclick="addnum()">
</form>
<span id="sumvalue"></span>
</body>
</html>


sum.jsp

<%
int num1 = Integer
.parseInt(request.getParameter("num1").toString());
int num2 = Integer
.parseInt(request.getParameter("num2").toString());
int sum = num1 + num2;
out.print("Sum is " + sum);
%>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
   <session-config>
        <session-timeout>
            30
   </session-timeout>
 </session-config>
 <welcome-file-list>
        <welcome-file>ajaxsample.html</welcome-file>
        </welcome-file-list>
 </web-app>

No comments:

Post a Comment

Simple JSP Ajax Tutorial

In this blog post, a simple JSP Ajax sample for adding two numbers.  Ajax is a method for returning a result without reloading the HTML pag...