Monday, March 14, 2011

JSP

JSP - Java Server Pages - In simplest words, it is a way of embedding JAVA inside HTML.

Suppose we want to display date and time on our web page. We can do this by simply adding a single line of java code inside our html code. For example,

<HTML>
<BODY>
Now it's <%= new java.util.Date() %>
</BODY>
</HTML>

The code in between <%= and %> will do what we want.

But remember this file should be saved as .jsp.

Saving it as a jsp file is not enough. So why? Let's look at what happens here.

This should reside in a jsp capable web server (for example, apache Tomcat).

So we need to save this jsp file inside the server (in Tomcat, inside webapps --> ROOT). Then open a browser and give it the path to the jsp file you just saved. (If it is saved in the local machine http://127.0.0.1/filename.jsp)

You will see the current date and time as the output.

What exactly happens here is, this jsp file is turned in to a java file and then compiled and loaded. Then if you reload the page after a while you'll see it displays new time. But when it is loaded for the second time it will not take a longer time as it does in loading for the first time. This is because, for the first time, it needs to be compiled, but when it is reloaded it need not to be re-compiled again. The java code inside <%= and %> are evaluated at run time, so new time will be displayed.

So in simple words, jsp enables developers to easily make dynamic web pages.