How to Create and Run a Simple Java Program in Eclipse


Introduction to Java Servlets - Part 2


Before reviewing this tutorial be sure to have the proper Java environment set up, as we learned how to do in my previous tutorial . Also I am recommending that you enhance your experience by doing a lot of independent research out on Google, in addition to what I am showing you here.

 

Before getting started on writing a program we need to create a project in Eclipse. Here is what my Workspace looks like. In the package explorer I have 3 projects set up. The one called test is what we will work on. We will write code in our workspace for the Hello.java file.



workspace

So let’s now create a project. Right click anywhere inside Package Explorer and choose new. We will see this first


new project

then press java project or just press file then new then java project.

then we will see this next



create java project

Fill in a name for the project, keep all else the same on the form and press finish. Next, expand the project folder to view all sub folders in the project, right click on src (this means source files), then choose new and then Class and press enter. This form will come up



create class

Here we are creating a class object where we will write our code. It is good practice (but not mandatory) to include a package name because we can have multiple classes in a package. Also a class name is mandatory. I chose the package name as test and for the class name please fill in as Hello and we do not need to include .java at the end of the name.Then check the box that says ‘public static void main’ and press Finish. Main(String args) is also referred to as the main method and we must have this inside our Main class object in order to run this class in Eclipse.

After Pressing Finish we have now created our Hello.java class and the minimal code will show up in our workspace. If we close the class by xing out of it then we can double click it in package explorer later and the code will reappear in our workspace. As we go along and create more complicated classes it will be okay if you copy and paste the code that I provide in a given tutorial. Right now we just want to get up and running.

Let us now understand the structure of our newly created class. Inside our public class named Hello we have one method called the main method. And inside this method we are asking the program to print out the phrase Hello World to our console.

Now let’s run the program. Be sure that the file is saved, press file save. Then right click on Hello.java in the package explorer and choose run as and then java application



run as java app

Look down below in the console and we will see Hello World.



console view

By now I am sure we have many more questions. My teaching methodology is to teach all the shortcuts so we can fast track our learning process. It is up to you to do homework and research any details about the process or things I may have inadvertently left out. I am only providing the basics. It is also okay to message me on facebook for quick questions.

 

Most tutorials leave you hanging at this point after creating the Hello World application. What to do next? We have just created a main class and ran it as a java application. This main class is also known as a POJO or plain old java object and we will use many of these types of classes along the way when building larger applications.

 

PART 2 - now I want to show another type of class we need to learn about. This is the servlet class. By understanding both types of classes up front, main (plain class) and servlet (web class), we can move from a POJO to a web application with servlet architecture. From my experience we can’t do much with POJOs in the beginning without lots of education. So I move right into Servlets because this way we can do web apps early on in our learning process. Take my word for it for now, because it is much more fun to work with servlets in my opinion. We can do more things as beginners sooner rather than later and thus keep our curiosity and interest going. Warning, it is very easy to give up on java, I did it many times, but rest assured it is worth it to keep plugging along.

 

Note, this below Servlet Tutorial, is very old and outdated. Read it to be informed but I recommend an easier Servlet Tutorial that does not require downloading Tomcat or configuring Web.xml click here.

Back to the Servlet class. But first, we are not set up to do servlets yet in this version of eclipse. We will need to start a new project and choose dynamic web project but as of now that choice is not available to us. So lets enable eclipse to do this

Please be advised that since I originally wrote this piece, that u may want to choose the most recent version of eclipse from the downloads section and also u may want to download the J2EE version so u don't have to modify the current version as described in these next steps.

Above our workspace Press help then install new software



install new software

In the 'work with' area delete what is there & copy and paste this:

https://download.eclipse.org/releases/luna

then press enter

then you will see that the program is pending..just wait patiently



install 2 jpg

then we see this



install 3 jpg

check the last box for Web, XML, Java EE. Here we are choosing to install only web enabled components so Eclipse will then be able to create a web app. It may take several minutes to load all the necessary components. We will see this:



calculating req 2.JPG

Don't worry if you see 'cannot perform operation', it will still load what we need. Then after a few minutes we see this next



install page

We are wanting mainly web developer tools and java EE...press next twice then review license and accept terms and click finish..it could now take up to 5 minutes to install. In lower right hand corner we will see this:



installing2.JPG

This is the end of the install instructions that u can skip by downloading the j2ee version of eclipse

When finished installing we will need to restart Eclipse and then all our web tools will be available to start our Servlet Web Application....So we will need to create a new project. This time choose file new then other, then open the web folder and choose dynamic web project



dynamic web project

After clicking dynamic web project we are going to have to name the project and choose a target runtime to run the project in. For this we need to download Tomcat binary core version and configure tomcat8 to run the Servlet project. So for project name input Servlet Example as shown and then hit new runtime and choose Apache Tomcat v 8.5. This part will not work until after downloading and extracting the tomcat zip file into a target folder which we reference in this configuration.



dynamic project runtime

This part might be a bit complicated so bear with me. Open the tomcat 8 folder and then choose the tomcat 8 sub folder for your runtime environment. Browse for the tomcat installation directory and choose this sub folder



dynamic tomcat 8

As we navigate through the process we see this notice. Click on open perspective and now we are ready to program a servlet class



dynamic open perspective

now we can see in upper right hand corner of our workspace that we have the Java perspective that we used for plain java and we jave the JavaEE perspective for web apps. So be sure you click on the right perspective for what you are working on. I have a third one here for Python which we will touch in another tutorial



perspectives

While creating our project be careful to press all the next buttons in the process. As you press next check create deployment descriptor web xml before clicking on Finish. Going back to our project explorer we now have our Servlet project ready to go using web dev components and in the Java EE perspective



servlet structure2

To build the servlet class we will use the same process we used previously to build our main class. Right click on src then select new but this time choose Servlet instead of Class. This screen will become visible



create servlet

Once again  use test as package and Hello as Class name. Then click next



create servlet2

uncheck Constructors from superclass, doPost, doGet and check service, then click finish. Here is what we see in our workspace. Do a file save and now we can tweek this code and run it



create servlet4

One last thing before running our servlet. Double click on web.xml file, click the source tab and copy the following html tags into the file right before the closing /web-app tag, save the file and close it. We have just mapped our servlet to the web app. Don't forget to do this whenever creating additional servlets

<servlet>    
    <servlet-name>Hello</servlet-name>
    <servlet-class>test.Hello</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>Hello</servlet-name>
    <url-pattern>/Hello</url-pattern>
  </servlet-mapping>

the completed web xml file should look like this:



web xml

I added some code to my service method then resaved the file. Now we are finally ready to run the servlet

protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        // we will enter some code here and the run the servlet
             //just do something simple like this
        System.out.println("Hello World");
        
    }

Right click on Hello.java, then run as, then run on server. The tomcat server will run this web app and your display will be on http://localhost:8080/Servlet_Example/Hello in your browser. Previously our POJO ran as a java application but this servlet runs as a web application on a real webserver currently at localhost. Now u can also open ur Google Chrome browser while Tomcat is still running and paste the above http address right into the browser to verify that it runs outside of tomcat.

A quick note: this class will not run properly as is, so comment out the following line by placing 2 slashes before the line...then re save file and re run class and it will work

//@WebServlet("/Hello")

This is it for now, click here for more on how to learn java . But remember that Servlets are a VERY important part of Java to know about. They pop up frequently in your travels.