JSP Servlet with AJAX Example
Table of Contents
JSP Servlet with AJAX Example
Ajax is a great feature implemented almost in all the websites in some way. It gives really a very good user interface, since things are loading/populating without refresh. It is commonly used in username availability checking, register/login page db level/business level validations etc.
We are going to use Ajax with JSP and servlet to calculate the EMI payable amount by giving amount, month and interest rate in single screen(without refreshing).
Requirements:
1. Include jQuery library (since we used $.get for ajax response)
2. Include Bootstrap libraries (for responsiveness)
Including jQuery and Bootstrap libraries in header section:
<link href="css/bootstrap.min.css" rel="stylesheet" type="text/css" /> <script src="js/jquery-1.12.3.min.js" type="text/javascript"> </script> <script src="js/bootstrap.min.js" type="text/javascript"> </script>
AJAX Script:
Reading all the values using jQuery val() method and $.get used to get the AJAX response.
CalculateEMI is the Servlet name and amount,rate, month are get parameters passed to CalculateEMI servlet for emi calculation business logics.
<script type="text/javascript"> $(document).ready(function() { $('button#emi').click(function(event) { var amount = $("#amount").val(); var rate = $("#rate").val(); var months = $("#months").val(); // AJAX REQUEST $.get('CalculateEMI', { amount : amount, rate : rate, month : months }, function(response) { $('#emiValue').text(response); }); event.preventDefault(); }); }); </script>
Note:event.preventDefault() used to avoid the page refresh after the ajax call.
index.jsp:
Remove the action parameter from the form tag.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>EMI Calculator</title> <link href="css/bootstrap.min.css" rel="stylesheet" type="text/css" /> <script src="js/jquery-1.12.3.min.js" type="text/javascript"> </script> <script src="js/bootstrap.min.js" type="text/javascript"> </script> <script type="text/javascript"> $(document).ready(function() { $('button#emi').click(function(event) { var amount = $("#amount").val(); var rate = $("#rate").val(); var months = $("#months").val(); // AJAX REQUEST $.get('CalculateEMI', { amount : amount, rate : rate, month : months }, function(response) { $('#emiValue').text(response); }); event.preventDefault(); }); }); </script> </head> <body> <nav class="navbar navbar-default navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> </div> <div id="navbar" class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li class="active"><a href="http://www.ngdeveloper.com">Javadomain.in</a></li> </ul> </div> <!--/.nav-collapse --> </div> </nav> <div class="container" style="margin-top: 150px;"> <div class="row"> <div class="form-group"> <form id="emi_form"> <fieldset> <!-- Form Name --> <legend>EMI Calculator</legend> <!-- Text input--> <div class="form-group"> <label class="col-md-4 control-label" for="amount">Enter the amount</label> <div class="col-md-5"> <input id="amount" name="amount" type="text" placeholder="" class="form-control input-md"> </div> </div> <!-- Text input--> <div class="form-group"> <label class="col-md-4 control-label" for="rate">Enter the Interest Rate</label> <div class="col-md-5"> <input id="rate" name="rate" type="text" placeholder="" class="form-control input-md"> </div> </div> <!-- Text input--> <div class="form-group"> <label class="col-md-4 control-label" for="month">Enter the Number of months</label> <div class="col-md-5"> <input id="months" name="month" type="text" placeholder="" class="form-control input-md"> </div> </div> <!-- Button --> <div class="form-group"> <label class="col-md-4 control-label" for="emi"></label> <div class="col-md-4"> <button id="emi" name="emi" class="btn btn-primary">Calculate EMI</button> </div> </div> </fieldset> </form> </div> </div> <div class="row"> <label class="col-md-4 control-label" for="month">EMI Amount Payable : </label> <div class="col-md-5" id="emiValue"></div> </div> </div> </body> </html>
CalculateEMI.java:
Emi calculation business logic’s are written in doGet() method.
write() method used to return the response to the AJAX.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String amount = request.getParameter("amount"); Double inter = Double.parseDouble(request.getParameter("rate")); String month = request.getParameter("month"); double loanAmount = Double.parseDouble(amount); double rateOfInterest =inter; int numberOfMonths = Integer.parseInt(month); double temp = 1200; //100*numberofmonths(12)) double interestPerMonth = rateOfInterest/temp; double onePlusInterestPerMonth = 1 + interestPerMonth; double powerOfOnePlusInterestPerMonth = Math.pow(onePlusInterestPerMonth,numberOfMonths); double powerofOnePlusInterestPerMonthMinusOne = powerOfOnePlusInterestPerMonth-1; double divides = powerOfOnePlusInterestPerMonth/powerofOnePlusInterestPerMonthMinusOne; double principleMultiplyInterestPerMonth = loanAmount * interestPerMonth; double totalEmi = principleMultiplyInterestPerMonth*divides; Double finalValue = Math.round( totalEmi * 100.0 ) / 100.0; response.setContentType("text/plain"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(finalValue.toString()); }
Project Structure:
Output: