Friday, 27 May 2016

Very Simple Example to a Servlet - Hello World Servlet

Hello everybody!

I am going to show you how to write your very first servlet code. So if you are new and looking for a easy yet useful start, you are in the right place.This is the code I wrote a few months ago when I started to get familiar with servlets, jsp, jsf and database operations. So a couple of more posts related to these subjects will be posted probably not too far from now. Let's get started.



Create your project and name it as you like. I named mine as "HelloWorldServlet1". Then under the "src" folder you should add a package that will keep your servlets in. Right click to "src" and select "package" option, then name it. My package name is "com.selen.servlet". The project folder structure will look like this after this step.


Now it is time to create the servlet. Right click to the package that you have just created. Select "Servlet class" and name it. (mine is HelloWorldServlet.java as you can see). There will be doGet and doPost merthods and servlet declaration in this file. You can delete the ones you will not use or update them. My servlet looks like below .


As you can see, doGet method in my servlet writes a welcome message by using some html codes in java codes. There is also a servlet declaration just before the class name by default. I commented out these line as I prefer to do my servlet declaration in the web.xml file. 

The next step is configuring the web.xml file. This file lets the program know which servlet is going to be run and organise what is going to be displayed in the url. The final version of my web.xml file is located below. You can also see some explanations about the code.


To run this code right click to the project name and choose Run As-> Run on Server. It will run it on the Tomcat Server. If you need any help how to integrate Tomcat Server with Eclipse or how to install Tomcat, you can check my previous post. After running the code you will get a result as below. You should understand how the url formed this way now.

Hope to see you in the next blog post!

Selen

No comments:

Post a Comment