After having set up your development environment, you are ready to begin. Let’s start with differentiating JSP from Servlets.
JSP vs Servlets
With the difference settled, let’s get started with the basics of JSP. A common question people ask is “What is a JSP File?” To put it simply, it is an HTML page with a little bit of Java code sprinkled in between. It’s a way to get dynamic content generated at runtime into your HTML pages. JSP Files are processed on the server, ay you have Tomcat or Glassfish or whatever you have installed. The final processed result is included in the HTML and then returned to the browser which initiated the request.
In order for the files to perform correctly, you should place them in the WebContent folder, with a .jsp extension. Now it’s like a regular website, which is why you can have as many JSP files as you want and you can even put them in sub directories just like HTML files, just that you’ll have a .jsp extension rather than .html.
Here is a sample code of a .jsp file:
<html> <body> <h2>Hello World!</h2> The time on server is <%= new java.util.Date() %> </body> </html>
To use java code we make use of “<” an angle bracket and then a “%”percentage sign. When you are opening the tag then you have to use an equal sign after the percent sign. After opening the java tag we create a new date object which will get the date set on the server and then as the tag is closed, the returned value is then included into the HTML.
Hello World on Eclipse
Open up Eclipse. So the first thing we need to do is create a new dynamic web project. Go to “File”, hover on “New” and click on “Dynamic Web Project”. A dialogue box will open up prompting you to enter your project details such as project name, location and the target runtime. Make sure that the target runtime is set for the Apache Tomcat version you have installed, and then click finish. You can name the project whatever you want, but for the purpose of this tutorial series I am going to name it “jspdemo”.
Once the project hasbeen created you can expand the project in the Project Explorer on the left and you’ll see a folder hierarchy like this:
In the beginning the Web Content folder will be empty but you’ll have to create a new file in there. Right click on the WebContent Folder and select new file. Name it whatever you want and click finish, I am going to name mine “helloworld.jsp”. With that Eclipse will create a completely blank file. Write the same code as above. Once you are done writing the code, got to the project explorer and right click on the helloworld.jsp file. Navigate to Run as and click on Run on Server. Eclipse will prompt you to choose a server and you’ll get a list of the available servers. Select the server you just configured and click on finish. Eclipse will run the file in the built-in browser.