Ajax Login Servlet

Ajax Login Servlet


Posted in : Java Posted on : November 8, 2011 at 7:31 PM Comments : [ 0 ]

In this tutorial you will learn about how to validate a login form using ajax.

Ajax Login Servlet

In this tutorial you will learn about how to validate a login form using ajax.

To do so here I am giving a simple example which will demonstrate you how to validate login form.

Most of the commercial websites need to first validate the user before to use their websites and also for the security reason it is required. So in the example given below at first I create a html file named login.html into which I add the reference of JavaScript file named ajaxFrmSbmt.js. You can use the full code of JavaScript by downloading from the "simonerodriguez.com". Further I call the 'getxmlHttpRequest()' on the event 'onsubmit' in the form tag and passed the parameter values according to the variables given as the parameter of this method. Next I created a Servlet named LoginServlet.java that will take the request of parameters and the response will be sent by the server and check the user name and password by hard coding. In this simple example two textbox is taken as to enter the value. When you will enter the text into the textbox and click on the submit button the form will be submitted and an alert box will displayed which displays the welcome message without refreshing the whole page.

Example :

login.html

<html>
<head>
<script type="text/javascript" src="js/ajaxFrmSbmt.js"></script>
<title></title>
</head>
<body>
<form name="form1" method="post" onsubmit="getxmlHttpRequest('LoginServlet', 'form1', 'message', 'please wait...'); return false;">
Enter name <input type="text" name="username"/><br>
Password <input type="password" name="password"/>
<input type="submit" value="submit"/>
</form>
<div id="message"></div>
</body>
</html>

ajaxFrmSbmt.js

function getxmlHttpRequest(servletName,formname,responsediv,responsemsg) {
var xmlhttp = false;
var x = this;
// For the browsers Mozilla/Safari/Ie7
if (window.XMLHttpRequest) {
x.xmlhttp = new XMLHttpRequest();
}
// for the lower version of IE
else if (window.ActiveXObject) {
x.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
x.xmlhttp.open('POST', servletName, true);
x.xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
x.xmlhttp.onreadystatechange = function() {
if (x.xmlhttp.readyState == 4)
{
updatepage(x.xmlhttp.responseText,responsediv);
}
else
{ 
updatepage(responsemsg,responsediv);

}
}
x.xmlhttp.send(getquerystring(formname));
}

function getquerystring(formname) {
var form = document.forms[formname];
var qstr = "";

function GetElemValue(name, value) {
qstr += (qstr.length > 0 ? "&" : "")
+ escape(name).replace(/\+/g, "%2B") + "="
+ escape(value ? value : "").replace(/\+/g, "%2B");
//+ escape(value ? value : "").replace(/\n/g, "%0D");
}

var elemArray = form.elements;
for (var i = 0; i < elemArray.length; i++) {
var element = elemArray[i];
var elemType = element.type.toUpperCase();
var elemName = element.name;
if (elemName) {
if (elemType == "TEXT" || elemType == "PASSWORD")
{
GetElemValue(elemName, element.value);
alert("welcome");
}
else if (elemType.indexOf("SELECT") != -1)
for (var j = 0; j < element.options.length; j++) {
var option = element.options[j];
if (option.selected)
GetElemValue(elemName,
option.value ? option.value : option.text);
}
}
}
return qstr;
}
function updatepage(str,responsediv){
document.getElementById(responsediv).innerHTML = str;
}

LoginServlet.java

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginServlet extends HttpServlet
{
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();

String uname= request.getParameter("username");
String psw= request.getParameter("password");

if(uname.equals("admin") && psw.equals("admin"))
{
out.println("You have successfully logged in");
}
else 
out.println("either user name or password is invalid");
}
}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>ajaxWithServlet</display-name>
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>LoginServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
</web-app>

Output :

When you will execute the above example you will get the output as :

When you will enter the value into the corresponding text boxes then the page will be as :

When you will click on submit button then an alert box will appear and after clicking on ok on the alert box page will look like as :

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics