Ajax Servlet Filter

Ajax Servlet Filter


Posted in : Java Posted on : November 11, 2011 at 6:34 PM Comments : [ 0 ]

In this tutorial you will learn how a servlet filter is used with ajax.

Ajax Servlet Filter

In this tutorial you will learn how a servlet filter is used with ajax.

Here I am giving the simple example which will demonstrate you about the above problem. In the example given below I create a class named FilterLoginServlet which implements the Filter class into which I did the hard code to verify the user name and password. For taking the user information I create a html file named filterLogin.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. 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 the message "welcome" after the string verified and the message "please enter correct information" after non verifying the string without refreshing the whole page.

Example :

filterLogin.html

<html>
<head>
<script type="text/javascript" src="js/ajaxFrmSbmt.js"></script>
<title>Ajax Servlet Filter</title>
</head>
<body>
<form name="form1" method="post" onsubmit="getxmlHttpRequest('LogFilterServlet', '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>

FilterLoginServlet.java

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class FilterLoginServlet implements Filter
{
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException
{
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
res.setContentType("text/html");
PrintWriter out = res.getWriter();

String uname= req.getParameter("username");
String psw= req.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");

chain.doFilter(request, response);
}
public void init(FilterConfig config)
{
System.out.println("Server is started");
}
public void destroy()
{
System.out.println("Server is stopped"); 
}
}

LogFilterServlet.java

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 LogFilterServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{ 
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
doGet(request, response);
}
}

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); 
if(element.value=="admin")
{
alert("welcome");
}
else
alert("Please enter correct information");
}
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;
}

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>

<filter>
<filter-name>FilterLoginServlet</filter-name>
<filter-class>FilterLoginServlet</filter-class>
</filter>

<filter-mapping>
<filter-name>FilterLoginServlet</filter-name>
<url-pattern>/LogFilterServlet</url-pattern>
</filter-mapping>

<servlet>
<servlet-name>LogFilterServlet</servlet-name>
<servlet-class>LogFilterServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>LogFilterServlet</servlet-name>
<url-pattern>/LogFilterServlet</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 like below

Then you will get the output like this :

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:


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

 
Tutorial Topics