J2EE – Running your first servlet application

What is J2EE?

Java Enterprise Edition or commonly known as J2EE is an extension of Java SE (Java Standard Edition, or core Java) for building distributed computing and web services. Unless you are building a web application else you will not be interested in J2EE.

What is Servlet?

A servlet is a class that extends the capability of server to responds to a HTTP request. This is the basic building block of building any web application.

What is Apache Maven?

Maven is a project management tool that allows you to manage your project build and dependencies.

Getting the right Eclipse IDE

Get Eclipse IDE for Java EE 👇https://www.eclipse.org/downloads/packages/release/indigo/sr2/eclipse-ide-java-ee-developers

Steps to create new Maven project

  1. At project explorer, right click to create a new Maven project.
  2. (Optional) Save project to default workspace location.
  3. Select an Archetype – org.apache.maven.archetypes (Group Id) – maven-archetype-webapp (Artifact Id).
  4. Enter your group and artifact name for your project and we are done!
  5. Download tomcat from this link: https://tomcat.apache.org/download-80.cgi
  6. Place the zipped folder in your local and extract the contents.
  7. Go to Server tab (or if this view is being closed, you can reopen it at Windows > Show View > Servers.
  8. Click on the link to create a new server.
  9. Depending on the tomcat version that you have just downloaded. For me its Tomcat V8.5 server.
  10. Click next and specify the directory of your tomcat (that is the extracted folder on your local) and click finish.

Adding dependency in pom.xml

  1. In our project there is a file called pom.xml. In here, we can tell eclipse to download the dependencies needed to build our application. One dependency we are going to need is the javaee-web-api
  2. Add the following in your pom.xml
<dependency>
	<groupId>javax</groupId>
	<artifactId>javaee-web-api</artifactId>
	<version>6.0</version>
	<scope>provided</scope>
</dependency>

Start writing our first servlet

  1. Let’s go back to our Project Explorer. Notice under Java Resources, we do not see src/main/java. So how are we going to add a new java class to it? To fix this, right click at your project folder (highest level in explorer) > Properties > Build Path > Order and Export tab and check both JRE and Maven Dependencies. Click Apply and Close. So now the src/main/java appears like magic!
  2. Right click /src/main/java and create a new java class.
  3. In our HelloServlet, we need to extend from class HttpServlet as we need to use both HttpServletRequest and HttpServletResponse.

/src/main/java/HelloServlet.java

package com.davidcheah.webapplication.servlet;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HelloServlet extends HttpServlet{
	public void service(HttpServletRequest request, HttpServletResponse response) {
		System.out.println("Hello World");
	}
}

Configuring our servlet in web.xml

  1. So we have our servlet ready but how are we going to call it in our application. To do this, we need to attach an url to our servlet.
  2. Go to /src/main/webapp/WEB-INF/web.xml and within the tag <web-app> add the following
<servlet>
  	<servlet-name>HelloServlet</servlet-name>
  	<servlet-class>com.davidcheah.webapplication.servlet.HelloServlet</servlet-class>
  </servlet>
  
  <servlet-mapping>
  	<servlet-name>HelloServlet</servlet-name>
  	<url-pattern>/helloworld</url-pattern>
  </servlet-mapping>

3. So for each servlet class, we have 2 tags, the <servlet> and <servlet-mapping> and both tags are linked together with a common <servlet-name>. The first tag contains the class path of our servlet and second tag defines the url associated to it.

Running our application

  1. Right click at your project name > Run As > Run on Server
  2. A web page should pop up showing Hello World. However this is not the servlet that we have build. Remember our servlet is linked to url /helloworld. So let’s enter the url http://localhost:8080/WebApplication/helloworld
  3. Nothing shows up! But check in your console and you should be able to spot a “hello world” printed.
  4. Now, this is quite boring and there’s nothing shown on the page itself. Let’s try to print on the page itself. For this we are going to use PrintWriter class from JavaSE. We are going to literally print html codes.
package com.davidcheah.webapplication.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HelloServlet extends HttpServlet {
	public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
		PrintWriter out = response.getWriter();
		out.println("<html><body><h1>Hello World</h1>");
		out.println("<p>The time is " + new Date() + "</p>");
		out.println("</body></html>");
		out.close();
	}
}

After re-running our application, you should see the following on the screen.

Conclusion

There you have it. We just run our first servlet application that was able to print to console, as well as display on the page itself.

Source Code

https://github.com/tattwei46/FirstServletApplication

About the author

Founder of tattweicheah.com. Loves music, sport and most importantly software development.

Leave a Reply

Your email address will not be published. Required fields are marked *