Introduction Java Servlet is the one of the most important Java technologies. It is the simplest model to build a complete Java J2EE Web Application. Furthermore, even for complex J2EE Web Application that uses Struts, Spring, EJB and etc, they are still using Servlet for certain purposes such as Servlet Filter, Listener and etc. Thus, it is just a good idea for you to have well-built understanding of Java Servlet. Prior reading this tutorial, it would be excellent if you have mastered the basic Java programming languages. At the completion of the tutorial, you are expected to comprehend the concept of the Java Servlet, be familiar with the ways to create Java Servlet using Eclipse 3.1.2, differences between POST and GET and should be ready to go to the next level. In this tutorial, we are going to create one dynamic web application that asks the user for first name and surname. Then the system should response by greeting the users. The tutorial consists of four main steps.
|
Introduction to Eclipse 3.1.2
Nowadays, many J2EE developers are using Eclipse as their IDE for Java programming language. One of the reasons is that Eclipse is free and is easily extendable. Yes, that is correct, there are plentiful plugins available in Internet for Eclipse. Additionally, the famous IBM WebSphere Application Developer for developing J2EE application in WebSphere is also implemented above the Eclipse framework.
Besides Java programming, Eclipse can also be used to edit any file such as C++, C or PHP and etc. You need to remember that Eclipse does not have any server embedded in it. Eclipse is just an editor. Well, let's start to explore on how Eclipse can assist you in creating a Java Servlet.
Creating New Web Application Project in Eclipse 3.1.2 with Web Tools Platform (WTP) Plug-in
Okay, for our tutorial, we are going to exercise Web Tools Platform (WTP) plugin. I would suggest you to download Web Tools Platform (WTP) together with Eclipse so you should not be bothered on how to install the plugin into Eclipse and etc. Ideally, if you download Eclipse without any plugin, it does not have any support for J2EE Development. That is the core reason why various vendors are implementing J2EE plugins for Eclipse. Web Tools Platform is not the only J2EE plugin available for Eclipse. There are numerous J2EE plugins available in Internet such as Lomboz from ObjectLearn, MyEclipse and etc. If you are interested to know deeper on Eclipse plugin, you can visit http://www.eclipseplugincentral.com/ for the complete list of available plugins for Eclipse.
To download Web Tools Platform (WTP), you can go to http://www.eclipse.org/webtools/ and you can download it together with Eclipse by choosing the download link on the left panel of that particular site. Web Tools Platform (WTP) plugin with Eclipse is approximately 182 MB. It will be in zip file and you will not have installation for it. You can extract it to C:\ and you can directly use Eclipse by double clicking the Eclipse.exe file in the extracted folder.
Unlike NetBeans, Eclipse does not have any server embedded in it thus, in order to create a Java Servlet in Eclipse; you need to install the server (for our tutorial, you need Apache Tomcat) as well as the Java Development Kit (JDK) from Sun.
Before going further to our tutorial, it would be good if you understand the concept of Java Servlet as explained in the next paragraphs.
Creating a Java Servlet means that you are required to deal with JSP (JavaServer Pages). JSP is actually a HTML but unlike HTML, JSP may have Java codes (usually we call it as Scriptlet) embedded in it. In short words, we may represent JSP as dynamic HTML. In Java J2EE Web Application, JSP plays as a front-end while Java Servlet is the controller that contains the business logics, complex algorithms and etc.
For example, consider "Online University Student Registration System" developed in Java J2EE Web Application, the registration page where you fill in your details such as your name, your address, your username and etc are actually a JSP page. Later on, when you have completed filling out all the details and you press the submit button, all the information will be sent to Java Servlet for further processes. Java Servlet receives this information, does the necessary processes such as validations, generating user id and etc and then keeps the information to database. After successfully saving the data to database, Java Servlet redirects the user to the success page where the user can log in to the system. Likewise, if there is an unexpected error occurred happening in the middle of student registration system's process, the user will be redirected to the error page.
Assuming that you have installed Eclipse with Web Tools Platform (WTP) Plugin, Java Development Kit 1.5 and Tomcat Server 5.5, let's start to create our first Java Servlet. Start Eclipse and you should see similar to below illustration in your screen. Yes, this is the main page of Eclipse.
To create our Java Servlet, we are required to create a Project called Dynamic Web Project. Go to your menu, choose New and Project. A wizard will be prompted to you.
Go to the Web and choose Dynamic Web Project and press Next. If you do not have Dynamic Web Project available, it means that Web Tools Platform (WTP) plugin is not correctly installed to Eclipse. Please re-download it or look at the documentation of Web Tools Platform (WTP) plugin for more details.
A wizard will be displayed to you. The wizard is mainly used to configure our Dynamic Web Project. You are allowed to name your Dynamic Web Project with any name that you wish but please consider to choose the name that is self-explanatory.
For our tutorial's sample, I am going to name my Dynamic Web Project as MyFirstServlet. There is an interesting point worth to be looked at in this wizard. You need to provide the Target Runtime. What does it mean? Well, it basically requests you to identify the server that you would like to use for this Dynamic Web Project; in this case, Apache Tomcat. You may try to click on the combo box to observe whether you have any existing server(s) or not. If not, you are required to create one server for your project. If this is the first time you run Eclipse, you should not have any server yet. So, click on the New button on the right side of the Target Runtime combo box. Remember, after defining one server, you can re-use it in other projects so you do not need to define new server in every project unless if you wish to use other servers than Tomcat such as Bea WebLogic and etc.
Creating Server Definition in Eclipse 3.1.2 If you have configured the server, you may skip this step. After you click on New button to choose a new server, another wizard should be displayed on top of the existing wizard. In this wizard, you are asked what server you wish to use. For our tutorial, we should use Apache Tomcat 5.5 so you need to select Apache Tomcat v5.5 from the list and press Next button. From the illustration below, it is obvious that there are other servers available for you to select such as Bea WebLogic, JBoss and etc. |
In the next wizard, we are required to provide the information on where our Apache Tomcat is located. In my machine, I extracted it on C:\tomcat-5.5.16 so I got to click on the Browse button on right side of the Tomcat installation directory textbox and we need to select the Tomcat folder for it. Additionally, you also need to provide on what Java Run Time (JRE) you want to use. If you have installed Java Development Kit (JDK), it should also install JRE automatically. Eclipse should be able to auto-detect and should provide you few options in the list. Choose the JRE that is installed together with the installation of your Java Development Kit (JDK). You can press Finish button and our server's configuration is completed.
Back to our Dynamic Web Project configuration, after configuring the server, we should have Tomcat 5.5 as one of the options in the combo box for Target Runtime. Please select the server that you just recently added or have configured and press Next button.
Next wizard is shown. We can ignore them and keep them as default. Press Next button.
Now, we are in the last step of our Dynamic Web Project configuration. For this wizard, you should not modify the Context Root albeit you are allowed to do so as to understand the concept of context root may be puzzling. You can leave them as default and when you are more familiar with Java programming, you may try to play around with it.
You can amend the Content Directory with any name that you wish. Normally, J2EE Developers will name it the same as the Project Name to increase the maintainability of the project. For this tutorial, we are not going to change it and we are going to keep it as default - WebContent. For your information, this directory is the place where all the deployment descriptor, JSP files, other configuration files are located. Press Finish button and we have completed our Dynamic Web Project configuration.
You should be able to see something like below illustration.
Implementation of Tutorial's Example For our tutorial, we are going to use index.jsp to demonstrate how to implement Java Servlet that greets the users. Index.jsp will be used to obtain the first name as well as the last name / surname of the users. For this case, textboxes should be adequate as first name and surname. However, it would be different case if we are required to get the country of origin of the users. The use of combobox would be more appropriate for choosing the country of origin as there are more than one choices to be chosen on. We are also required to create one more JSP file called greeting.jsp to greet the users. Hence, the flow would be index.jsp -> GreetingServlet -> greeting.jsp. In short, index.jsp will first be displayed to users, the users then fill his or her first and surname in index.jsp and press Submit button. This information is sent to our Java Servlet and our Java Servlet redirects the users to the greeting.jsp. |
Now, we need to create a JSP file (we will call it index.jsp for our tutorial) to allow the user to enter his or her first name and surname. Right click on your WebContent, choose New and Other. A wizard is prompted to you to choose what type of files you want to include into your Dynamic Web Project.
Choose JSP and press Next button.
You can name your JSP with any name that you wish but for our tutorial sample, I am going to name it index.jsp.
The last step of configuring our JSP file is not really important. We can ignore it which also means that we accept the default template from Eclipse. Press Finish button and you should have index.jsp under your WebContent folder.
If you double click on your JSP, your screen should look similar as below.
In index.jsp, we need to have two textboxes for getting the user's input and a button to submit the information to our Java Servlet. After pressing the button, the user should be redirected into greeting page. Now, let's create the textbox. The textbox command would be the same as HTML command that is <input type="text" value="50"> and so on. Please remember that every textbox or components whose values would like to be passed into Java Servlet must be within <form></form> tag. Thus, please add below lines of codes into your index.jsp after the <h1></h1> tag.
Now, we have <form> and </form> HTML tag. Inside <form></form> tag, we need to specify few values such as action and method. Action is used to allow the JSP page knows which Java Servlet to be called on the invocation of submit button and the method is used to select the preferred way to pass your information to Java Servlet. This method attribute will be discussed further in the later phase.
However, if you press the Submit button, it should not go anywhere as we do not specify the action attribute of the <form></form> tag. Later on, if we want this JSP to call our Java Servlet, we need to modify this action attribute to our Java Servlet URL mapping.
We also have two textboxes now i.e <input type="text" name="firstName" size="20"> and <input type="text" name="surname" size="20">. There are few important things that you need to pay attention here. The name attribute for these textbox component are extremely important; in our index.jsp, it would be firstName and surname. These keywords are used to obtain the information in Java Servlet from the JSP page. It would be demonstrated in later phase once you have seen the implementation of the Java Servlet. The type is used to define what kind of component it is; text represents textboxes, button represents a button, image represents a picture and etc. The size is used to determine the width of the textbox. For more information, you can reference to the HTML tag which is available in Internet.
Now, as Tomcat is run in its own and is not integrated within Eclipse, we need to start Tomcat manually. Albeit that we can actually run Tomcat within Eclipse (with few configuration), it is suggested that it would be better to start and shutdown Tomcat manually as it offers you more flexibility and should allow you to understand how Tomcat works better. Yes, it may not be that user-friendly but our intention is to make you understand the concept of Java Servlet.
You need to export your Dynamic Web Project into .WAR file first before deploying into Tomcat. WAR (WebArchive File) is actually similar to a ZIP-compressed file that contains all of your necessary Web Project's files. It should be extracted and deployed by Tomcat when Tomcat runs.
Right click on your Dynamic Web Project, choose Export.
Another wizard will be prompted to you. Choose WAR file and press Next button.
In the next step of exporting your Dynamic Web Project into WAR file, you need to provide Web Module and Destination information. Web Module is your Dynamic Web Project name and the Destination will be the location where your WAR file is located.
You need to remember one thing. To deploy WAR file to Tomcat, the WAR file MUST be in the webapps folder of the Tomcat. This is the default behavior of Tomcat. So if I have extracted my Tomcat into C:\tomcat-5.5.16, I should specify the destination of my WAR file into C:\tomcat-5.5.16\webapps and then Press Finish button.
So the wizard should look like below.
Overwrite existing file should always be ticked as the older and existing WAR file will be overwritten with the new WAR file. It should be obvious when you are re-deploying your Dynamic Web Project into Tomcat.
Export source files option enables you to include all your source codes (JAVA files) with the WAR file. While it is not recommended due to security issue, this would be useful if you are about to deliver the project to the clients as they definitely requires you to pass them the source codes.
How to Start Tomcat Manually
If you have successfully configured Tomcat, you should have a bin folder of Tomcat. Remember that you need to download the Tomcat from Apache website in the form of zip file. Do not download the .exe file as it would be good if you have a manual hands-on experience on this. It should help you to understand how Tomcat works.
I have extracted my Tomcat into C:\tomcat-5.5.16. Thus, I should have a bin folder that is C:\tomcat-5.5.16\bin.
If you pay attention carefully, you would see there is startup.bat and shutdown.bat. These two files are used to start Tomcat and shutdown Tomcat respectively.
Double click on startup.bat, a new Tomcat console should open. Watch the console carefully and you will see something interesting.
You should see that it displays "Deploying web application archive MyFirstServlet.war". Tomcat always checks its webapps folder whether is there any WAR file. If so, it will extract it and deploy it to its container so that we can run it after Tomcat started. Tomcat will be started if you have seen the message "Server startup in N ms". If you do not have any WAR file, the above message should not be displayed.
Now, open your browser and go to http://localhost:8080.
This means that we have started Tomcat correctly. As we have already deployed our MyFirstServlet, execute it by http://localhost:8080/[yourwebappname] so it would be http://localhost:8080/MyFirstServlet.
Awesome! Try to press Submit button, it should do nothing as we have not specified any action in our <form></form> tag. Next, we need to modify our index.jsp to call our Java Servlet to greet the user and to redirect the user to the success page.
Please remember not to shutdown the Tomcat by clicking on the close window on the Tomcat console. Please use the shutdown.bat instead as it helps Tomcat to gradually shutting down itself.
Now, let's create our Java Servlet. You can right click on the src folder (this is your source folder) and choose New and Others. A wizard will be prompted to you to configure your Java Servlet.
Go to the Web, choose Servlet and press Next button.
In this wizard, you may define the package for your Java Servlet. Normally, we use Package to group a few Java files that has the same functionalities. For example, if I have StringUtil.java for String manipulation and EncodingAlgorithmUtil.java for encoding, I will locate them under the same package called "com.mycompanyname.util" as they both are actually utility classes. So as this is our first Java Servlet, let's create one package called "com.mycompany.servlet". The class name is basically your Java Servlet name. To make it self-explanatory, I name it GreetingServlet. You can leave other configuration as they are.
Then press Next button.
In the second step of the Java Servlet configuration, you may or may not provide any description that you want for your Java Servlet. Initialization Parameter is extremely useful if your Java Servlet need to have initial value before being executed. The URL mapping is used to identify on how the Java Servlet should be called. This is the URL that is called in your <form></form> tag in JSP file. If you set the URL Mapping into /test/GreetingServlet, you need to call it as /test/GreetingServlet from your <form></form> tag in your JSP file.
In the last step of Java Servlet configuration, we can keep them as they are. This wizard allows you to modify your Java Servlet's methods. Press Finish button and we have created a non-functional Java Servlet.
If you have followed correctly, you should have a GreetingServlet.java similar to the illustration below.
<form action=" " method="POST"> First Name: <input type="text" name="firstName" size="20"><br> Surname: <input type="text" name="surname" size="20"> <br><br> <input type="submit" value="Submit"> </form>
Implementation of Java Servlet
Back to our Eclipse and modify your index.jsp to something like below.
<form action="GreetingServlet" method="POST"> First Name: <input type="text" name="firstName" size="20"><br> Surname: <input type="text" name="surname" size="20"> <br><br> <input type="submit" value="Submit"> </form> |
It means that every time we execute the Submit button in our JSP, it will call GreetingServlet that we created earlier. However, now, our Java Servlet actually do nothing. We need to modify our GreetingServlet.java as well.
This GreetingServlet.java contains our implementation of the Java Servlet. If you carefully pay attention to this file, you should realize that this class extends HttpServlet. So wherever you found Java classes that extends HttpServlet, those classes must definitely be a Java Servlet and there must be an entry in web.xml.
There are few Java methods created by default in GreetingServlet.java i.e.
protected void doGet(HttpServletRequest request, HttpServletResponse response) protected void doPost(HttpServletRequest request, HttpServletResponse response) |
and many more.
Let's focus on the doGet and doPost methods as these two methods are the most important. Do you remember that in our <form></form> tag, we actually specify the method attribute as POST? For your information, we can also set the method in the <form></form> tag into GET. If we specify it as POST, the doPost method will be called. On the other hand, if we specify the <form> tag as GET, doGet method will be executed. Then, what would be the difference between GET and POST?
Each method has its own advantages and disadvantages. GET has limited length for the information that is submitted but it is easily appended on the last URL of your Java Servlet. POST does not have any limitation of the length of information sent and it is hidden from the URL. For example, GET will display something like http://localhost:7001/MyFirstServlet/GreetingServlet?firstName=david&surname=test while POST would not display firstName and surname in the end of the URL. POST has URL like "http://localhost:7001/MyFirstServlet/GreetingServlet". It is obvious that GET may have some issues on security as everyone may clearly see the information sent to the Java Servlet. POST would be a better choice but sometimes, there would just be a situation where we need to use GET to make our development easier. I am sure that as you go along, you will meet a situation where you need to use GET for sending some information to Servlet.
As our JSP used POST, let's add some Java codes into our doPost method. Add these two lines into your doPost method so it should be like below.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String firstName = request.getParameter("firstName").toString(); System.out.println("firstName = " + firstName); } String firstName = request.getParameter("firstName").toString(); |
What does above code means? If you remember, the textbox that we created in our JSP contains the name attribute.
<input type="text" name="firstName" size="20"> |
This is where the name attribute is useful. We can get the value entered by the user in the index.jsp by executing request.getParameter("firstName"). Remember that firstName is case sensitive so firstName is different with FirstName or firstname. The next line of code is used to print out the value into your Tomcat console.
System.out.println("firstName = " + firstName); |
Okay, let's see how the index.jsp works with our incomplete Java Servlet now. Right-click your Dynamic Web Project, choose Export and choose WAR file and keep the Destination and Web Module same as before (remember to tick the Overwrite existing file in the final step of your WAR export wizard) then press Finish button. Then pay attention to your Tomcat carefully. Remember that Tomcat AUTOMATICALL re-deploy your application if it found a new WAR file is located in its webapps folder.
After few seconds, Tomcat will detect that the WAR file has changed and it automatically re-deploy it as shown on illustration below.
Now, try to go to your browser and go to http://localhost:8080/MyFirstServlet again, provide your first name and surname and try to press the Submit button and see the Tomcat console on what's happening.
After pressing Submit button, it goes to blank page. This is happening because we have not specified the successful page.
And the Tomcat console has something interesting to look at.
It displays "firstName = David". It means that our doPost implementation of our Java Servlet has been successfully executed. Try to play around with it and provide with few different first names and pay attention to your Tomcat console.
Now, our Java Servlet has been proven to execute successfully but it has not greeted the user properly. After pressing Submit button, it goes to blank page. We need to modify it to go to success page. Ok, let's get back to our Eclipse.
Please modify your doPost method in your GreetingServlet.java into below codes.
response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); String firstName = request.getParameter("firstName").toString(); String surname = request.getParameter("surname").toString(); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet GreetingServlet</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Servlet GreetingServlet at " + request.getContextPath () + "</h1>"); out.println("<p>Welcome " + firstName + " " + surname + "</p>"); out.println("</body>"); out.println("</html>"); out.close(); |
Let's see on what the codes do.
String firstName = request.getParameter("firstName").toString(); String surname = request.getParameter("surname").toString(); |
The two lines above are used to get the firstname and the lastname from our JSP.
Then, these two variables are used and displayed into JSP and located in below codes. The out.println(""); is used to render the HTML into JSP page.
out.println("<html>"); out.println("<head>"); out.println("<title>Servlet GreetingServlet</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Servlet GreetingServlet at " + request.getContextPath () + "</h1>"); out.println("<p>Welcome " + firstName + " " + surname + "</p>"); out.println("</body>"); out.println("</html>"); |
You need to re-deploy your Dynamic Web Project into Tomcat (by exporting it into WAR file) and refresh your Internet Browser.
However, there is a little problem. PrintWriter may be red-underlined by Eclipse as we have not imported the necessary packages for it. Red-underlined means that it is syntax-error and we should fix it before exporting it into WAR file for deployment. Do not be afraid, click on the symbol on the left side of the codes and choose "Import PrintWriter (java.io)". Yes, IDE is supposed to help your programming easier and fun. If you develop it in less sophisticated IDE such as Notepad, you need to figure out by yourself on what import statement that you need to insert for PrintWriter class.
Okay, please re-deploy your Dynamic Web Project by exporting it into WAR file again as described in earlier discussion. Wait until Tomcat console has shown that it has been re-deployed, refresh your browser and try to press Submit button again and see what's happening now.
My final screen looks like
Congratulations, you have successfully created your Java Servlet.
How to Shutdown Tomcat Manually
Shutting down Tomcat is simple. You can double click on the shutdown.bat in your Tomcat's bin folder. It will open another "closing" console and after few seconds, both consoles will be disappeared and you should not be able to try to access http://localhost:8080 anymore.
Conclusion
Well, I am sure that you now have been able to create a Servlet using Eclipse 3.1.2 with the help of Web Tools Platform (WTP) plugin. By reading this tutorial, you should be able to send information to Java Servlet, know how to get this information from your Java Servlet and redirect the user to the success page. However, you should practice more and more as your skills will be improved along your experiences. There are still a lot of things in Java world that you need to know such as Filter, Listener, Struts, EJB and etc. If you grab the concept, you are good to go to the next level. I wish you all the best luck
You can find the NetBeans project for the tutorial source codes here.
The README file for the sources is available here.