May 14, 2011

Ajax POST request example - Barebones (with Java on the server side)

1) Create a JSP, PostExample.jsp and add it to the WebContent folder of the web application


<html>
<head>
<title>Barebones Ajax - Post Example</title>


<script type="text/javascript">


var request = null;


function createRequest() {


try {
request = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
    request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
    try {
      request = new ActiveXObject("Microsoft.XMLHTTP");
    } catch (failed) {
  request = null;
         }
    }
}

if (request == null) {  alert("Error creating request object");   }
}


function doLogin() {
createRequest();
request.open("POST", "login", true);
request.onreadystatechange = updatePage;
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
request.send("username="+ document.forms[0].elements[0].value 
+ "&password="+ document.forms[0].elements[1].value);
}


var updatePage = function() {
if (request.readyState == 4) {
if (request.status == 200) {

        var responseStr = request.responseText;
    document.getElementById('message').innerHTML = responseStr;
}
}
}
</script>
</head>
<body>


<h1>Welcome to MyWebsite.com</h1>
<h3>Enter your Login Details</h3>


<form>
<label>Username</label>: <input type="text" name="username" /><br/><br/>
<label>Password</label>: <input type="password" name="password"><br/><br/>
<input type="button" value="Submit" onclick="javascript:doLogin();"/> 
</form>
<br/>
<div id="message"></div>


</body>
</html>


2) Create a servlet, LoginServlet.java and add it to the src folder of the web application


import java.io.*;
import javax.servlet.http.*;


public class LoginServlet extends HttpServlet {

public void doPost (HttpServletRequest req, HttpServletResponse res) throws IOException {

String username = req.getParameter("username");
String password = req.getParameter("password");

PrintWriter out = res.getWriter();

if (username.equals("dinesh") && (password.equals("dinesh"))) {
out.print("<span style=\"color:green;\">The username/password is Correct</span>");
} else {
out.print("<span style=\"color:red;\">The username/password is Incorrect</span>");
}
}
}


3) Configure the servlet in the web.xml file,


<servlet>
   <servlet-name>login</servlet-name>
   <servlet-class>LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>login</servlet-name>
   <url-pattern>/login</url-pattern>
</servlet-mapping>


4) Test the example with the following URL in the browser,

http://localhost:8080/WebAppName/login

No comments:

Post a Comment