Hi!

For the first post I’m going to write a short tutorial on how to implement jQuery “the Write Less, Do More, JavaScript Library” into your JSP (JavaServer Pages) pages. Since i did not find anything similar on the web I’ve decided to write something about it. I hope you’ll find it interesting.

Client side code

We will create a simple form with one text input and a button to submit the data to the server. The server will calculate the square root of the entered number and return back the result without a page refresh.

HTML code (index.jsp or index.html)

<html>
<head>
	<title>Simple jQuery and JSP example</title>
	<script src="jquery-1.3.2.min.js" type="text/javascript"></script>
	<script src="script.js" type="text/javascript"></script>
</head>
<body>
<form id="form" action="calculate.jsp" method="post">
	Enter number:
	<input id="number" type="text" name="number" />

	<input id="submit" type="submit" value="Calculate Square Root" name="submit"/>
</form>
<p id="result"></p>
</body>
</html>

JavaScript (script.js)

$(document).ready(function() {
	$('#form').submit(function() {
		var number = $('#number').val();

		$.ajax({
			type: 		"post",
			url: 		"calculate.jsp",
			data: 		"number=" + number,
			success:	function(msg) {

				$('#result').hide();

				$("#result").html("<h3>" + msg + "</h3>")
				.fadeIn("slow");
			}
		});

	return false;
	});
});

I think the code is readable and simple.

When the DOM is ready and submit button on form with id “form” is clicked, we assign whatever it is in the input with id “number”, to new variable number. number is then passed to page “calculate.jsp”, through method “post”.

When the data is calculated, we hide the paragraph “result”, and slowly fade in the result, we’ ve got from “calculate.jsp”.

You can almost read the code as a normal text. It’s that simple.

Server side code

Code (calculate.jsp)

<?xml version="1.0" encoding="UTF-8" ?>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
int number = 0;

if(request.getParameter("number").matches("[\d]+")) {
	number = Integer.parseInt(request.getParameter("number"));
	out.println("Square root of " + number + " is " + Math.sqrt(number));
} else {
	out.println("Enter a number!");
}
%>

The code is pretty straight-forward. We get parameter with name “name”, check if it’s a number with .matches(“[\d]+”), parse it into integer, call Math function sqrt and print out the result or error.

Learn more about jQuery and JSPs.

About these ads