We can do this with AJAX.
AJAX is a standardized Javascript API for sending HTTP requests to the server and handling the response. For the server, the HTTP request sent from AJAX looks no different from the one sent by a browser. Therefore any Servlet can handle a AJAX request.
Let us update out example to use AJAX to do server-side age check.
Update the HelloWorld.java Servlet to do an age check (see below):
package org.confucius;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HelloWorld extends HttpServlet{
public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
int year = Integer.parseInt(request.getParameter("year"));
if (year > 1995)
response.getWriter().println("You are underage!");
else
response.getWriter().println("You may enter!");
}
}
Update web.xml to redirect age-check requests to HelloWorld Servlet:
<web-app>
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>org.confucius.HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/age-check</url-pattern>
</servlet-mapping>
</web-app>
Now update HelloWorld.jsp to use AJAX:
<html>
<head>
<script type="text/javascript">
function ageCheck()
{
year = document.getElementById("birthdate").value.substring(0,4);
// Create AJAX object
var xmlhttp;
if (window.XMLHttpRequest)
xmlhttp=new XMLHttpRequest(); // IE7+, Firefox, Chrome, Opera, Safari
else
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); // IE6, IE5
// Associate a method for AJAX response
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200) // Successful response
alert(xmlhttp.responseText);
}
// Send AJAX request
xmlhttp.open("GET","http://localhost:8080/HelloWorld/age-check?year="+year,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
Enter your birthday (yyyy-mm-dd): <input type="text" id="birthdate"/> <button type="button" onclick="ageCheck()">Check</button>
</form>
</body>
</html>
Now if you rebuild and deploy HelloWorld.war - you will be able to age check with an AJAX call to the Servlet.
Note: Instead of copying the HelloWorld.war each time to the /webapps directory, you can use the Tomcat Manager to undeploy/redeploy.
To do this:
Go to http://localhost:8080, click on the Manager App - you can login using the admin you created earlier (see your tomcat_home/conf/tomcat-users.xml file)
No comments:
Post a Comment