Hello World Example in JSP with Explanation

Hello World Example in JSP
The following illustrates a Hello World! example in JSP with explanation. It is very easy to code in JSP than in servlets. This is what most people say. It is absolutely right. There is a lot of variation both in length as well as ease between a JSP program and a Servlet program. You can easily understand what is most noticing about JSP in this post.


[*] The most notable factor of the JSP is that we don't need to restart Tomcat upon JSP modification.

How cool is it sounding? We are saying a bye-bye to restarting the tomcat. But when you create the project folder when the Tomcat has already started, you'll need to restart Tomcat because the tomcat doesn't know anything about the folder when it is running, it comes to know about it only when it starts.

Folder structure

A very simple folder structure can be noted for JSP. See here.

hellojsp
           |_ index.jsp
           |_ WEB-INF
                              |_ web.xml
That's it for the Hello World JSP program!

Deployment Descriptor - web.xml


<web-app></web-app>

See above, how easy the deployment descriptor file is. I have written nothing except starting and closing the <web-app> tag. This is necessary because Tomcat will be searching for the web.xml whenever the user makes a request. The <web-app> tag in this indicates that this is a web application. This is mandatory though you don't write any thing in this tag.

index.jsp


<html>
    <head>
        <title>Hello World JSP program</title>
    </head>
  
    <body>
        <%= "<h1>Hello World!</h1>" %>
    </body>
</html>

Explaining the JSP file

As you can see the file is looking like a HTML file. The symbols, <%= and %> might look wierd but if you understand they are easy. JSP expressions are enclosed with in these. Therefore dynamic content can be written here. Simple is that. The HTML tags can easily be understood. Note that only one expression can be enclosed with in this tag. If you want to write more expressions more tags are needed. For instance, if you want to print another line, then you need to enclose it within another <%= and %> symbols.

Now, the message Hello World! is printed on the web page and this message is enclosed with in the <h1> tag to make it appear larger.

That is it. In this way you can develop a simple Hello World JSP example with this 2 simple files. Isn't it easy? Hope this helps.

No comments: