Java Web Application Tutorial for Beginners

Web Applications are used to create dynamic websites. Java provides support for web application through Servlets and JSPs. We can create a website with static HTML pages but when we want information to be dynamic, we need web application.

The aim of this article is to provide basic details of different components in Web Application and how can we use Servlet and JSP to create our first java web application.

  1. Web Server and Client
  2. HTML and HTTP
  3. Understanding URL
  4. Why we need Servlet and JSPs?
  5. First Web Application with Servlet and JSP
  6. Web Container
  7. Web Application Directory Structure
  8. Deployment Descriptor

Web Server and Client

Web Server is a software that can process the client request and send the response back to the client. For example, Apache is one of the most widely used web server. Web Server runs on some physical machine and listens to client request on specific port.

A web client is a software that helps in communicating with the server. Some of the most widely used web clients are Firefox, Google Chrome, Safari etc. When we request something from server (through URL), web client takes care of creating a request and sending it to server and then parsing the server response and present it to the user.

HTML and HTTP

Web Server and Web Client are two separate softwares, so there should be some common language for communication. HTML is the common language between server and client and stands for HyperText Markup Language.

Web server and client needs a common communication protocol, HTTP (HyperText Transfer Protocol) is the communication protocol between server and client. HTTP runs on top of TCP/IP communication protocol.

Some of the important parts of HTTP Request are:

  • HTTP Method – action to be performed, usually GET, POST, PUT etc.
  • URL – Page to access
  • Form Parameters – similar to arguments in a java method, for example user,password details from login page.

Sample HTTP Request:

GET /FirstServletProject/jsps/hello.jsp HTTP/1.1
Host: localhost:8080
Cache-Control: no-cache

Some of the important parts of HTTP Response are:

  • Status Code – an integer to indicate whether the request was success or not. Some of the well known status codes are 200 for success, 404 for Not Found and 403 for Access Forbidden.
  • Content Type – text, html, image, pdf etc. Also known as MIME type
  • Content – actual data that is rendered by client and shown to user.

Sample HTTP Response:

200 OK
Date: Wed, 07 Aug 2013 19:55:50 GMT
Server: Apache-Coyote/1.1
Content-Length: 309
Content-Type: text/html;charset=US-ASCII

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Hello</title>
</head>
<body>
<h2>Hi There!</h2>
<br>
<h3>Date=Wed Aug 07 12:57:55 PDT 2013
</h3>
</body>
</html>

MIME Type or Content Type: If you see above sample HTTP response header, it contains tag “Content-Type”. It’s also called MIME type and server sends it to client to let them know the kind of data it’s sending. It helps client in rendering the data for user. Some of the mostly used mime types are text/html, text/xml, application/xml etc.

Understanding URL

URL is acronym of Universal Resource Locator and it’s used to locate the server and resource. Every resource on the web has it’s own unique address. Let’s see parts of URL with an example.

http://localhost:8080/FirstServletProject/jsps/hello.jsp

http:// – This is the first part of URL and provides the communication protocol to be used in server-client communication.

localhost – The unique address of the server, most of the times it’s the hostname of the server that maps to unique IP address. Sometimes multiple hostnames point to same IP addresses and web server virtual host takes care of sending request to the particular server instance.

8080 – This is the port on which server is listening, it’s optional and if we don’t provide it in URL then request goes to the default port of the protocol. Port numbers 0 to 1023 are reserved ports for well known services, for example 80 for HTTP, 443 for HTTPS, 21 for FTP etc.

FirstServletProject/jsps/hello.jsp – Resource requested from server. It can be static html, pdf, JSP, servlets, PHP etc.

Why we need Servlet and JSPs?

Web servers are good for static contents HTML pages but they don’t know how to generate dynamic content or how to save data into databases, so we need another tool that we can use to generate dynamic content. There are several programming languages for dynamic content like PHP, Python, Ruby on Rails, Java Servlets and JSPs.

Java Servlet and JSPs are server side technologies to extend the capability of web servers by providing support for dynamic response and data persistence.

First Web Application with Servlet and JSP

We will use “Eclipse IDE for Java EE Developers” for creating our first servlet application. Since servlet is a server side technology, we will need a web container that supports Servlet technology, so we will use Apache Tomcat server. It’s very easy to setup and I am leaving that part to yourself.

For ease of development, we can add configure Tomcat with Eclipse, it helps in easy deployment and running applications.

Go to Eclipse Preference and select Server Runtime Environments and select the version of your tomcat server, mine is Tomcat 7.

Eclipse-with-Tomcat

Provide the apache tomcat directory location and JRE information to add the runtime environment.

Now go to the Servers view and create a new server like below image pointing to the above added runtime environment.

Eclipse-New-Server-Tomcat

Note: If Servers tab is not visible, then you can select Window > Show View > Servers so that it will be visible in Eclipse window. Try stopping and starting server to make sure it’s working fine. If you have already started the server from terminal, then you will have to stop if from terminal and then start it from Eclipse else it won’t work perfectly.

Now we are ready with our setup to create first servlet and run it on tomcat server.

Select File > New > Dynamic Web Project and use below image to provide runtime as the server we added in last step and module version as 3.0 to create our servlet using Servlet 3.0 specs.

First-Servlet-dynamic-web-project

You can directly click Finish button to create the project or you can click on Next buttons to check for other options.

Now select File > New > Servlet and use below image to create our first servlet. Again we can click finish or we can check other options through next button.

first-servlet

When we click on Finish button, it generates our Servlet skeleton code, so we don’t need to type in all the different methods and imports in servlet and saves us time.

Now we will add some HTML with dynamic data code in doGet() method that will be invoked for HTTP GET request. Our first servlet looks like below.

package com.journaldev.first;

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

import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class FirstServlet
 */
@WebServlet(description = "My First Servlet", urlPatterns = { "/FirstServlet" , "/FirstServlet.do"}, initParams = {@WebInitParam(name="id",value="1"),@WebInitParam(name="name",value="pankaj")})
public class FirstServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	public static final String HTML_START="<html><body>";
	public static final String HTML_END="</body></html>";
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public FirstServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		Date date = new Date();
		out.println(HTML_START + "<h2>Hi There!</h2><br/><h3>Date="+date +"</h3>"+HTML_END);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}

Before Servlet 3, we need to provide the url pattern information in web application deployment descriptor but servlet 3.0 uses java annotations that is easy to understand and chances of errors are less.

Now chose Run > Run on Server option from servlet editor window and use below images for the options.

servlet-eclipse-server

servlet-eclipse-server-webapps

After clicking finish, browser will open in Eclipse and we get following HTML page.

first-servlet-run

You can refresh it to check that Date is dynamic and keeps on changing, you can open it outside of Eclipse also in any other browser.

So servlet is used to generate HTML and send it in response, if you will look into the doGet() implementation, we are actually creating an HTML document as writing it in response PrintWriter object and we are adding dynamic information where we need it.

It’s good for start but if the response is huge with lot of dynamic data, it’s error prone and hard to read and maintain. This is the primary reason for introduction of JSPs.

JSP is also server side technology and it’s like HTML with additional features to add dynamic content where we need it.
JSPs are good for presentation because it’s easy to write because it’s like HTML. Here is our first JSP program that does the same thing like above servlet.

<%@page import="java.util.Date"%>
<%@ page language="java" contentType="text/html; charset=US-ASCII"
    pageEncoding="US-ASCII"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Hello</title>
</head>
<body>
<h2>Hi There!</h2>
<br>
<h3>Date=<%= new Date() %>
</h3>
</body>
</html>

If we run above JSP, we get output like below image.

first-jsp-run

The final project hierarchy looks like below image in Eclipse.

project-hierarchy-servlet

Download FirstServlet Project

We will look into Servlets and JSPs in more detail in future posts but before concluding this post, we should have good understanding of some of the aspects of java web applications.

Web Container

Tomcat is a web container, when a request is made from Client to web server, it passes the request to web container and it’s web container job to find the correct resource to handle the request (servlet or JSP) and then use the response from the resource to generate the response and provide it to web server. Then web server sends the response back to the client.

When web container gets the request and if it’s for servlet then container creates two Objects HTTPServletRequest and HTTPServletResponse. Then it finds the correct servlet based on the URL and creates a thread for the request. Then it invokes the servlet service() method and based on the HTTP method service() method invokes doGet() or doPost() methods. Servlet methods generate the dynamic page and write it to response. Once servlet thread is complete, container converts the response to HTTP response and send it back to client.

Some of the important work done by web container are:

  • Communication Support – Container provides easy way of communication between web server and the servlets and JSPs. Because of container, we don’t need to build a server socket to listen for any request from web server, parse the request and generate response. All these important and complex tasks are done by container and all we need to focus is on our business logic for our applications.
  • Lifecycle and Resource Management – Container takes care of managing the life cycle of servlet. Container takes care of loading the servlets into memory, initializing servlets, invoking servlet methods and destroying them. Container also provides utility like JNDI for resource pooling and management.
  • Multithreading Support – Container creates new thread for every request to the servlet and when it’s processed the thread dies. So servlets are not initialized for each request and saves time and memory.
  • JSP Support – JSPs doesn’t look like normal java classes and web container provides support for JSP. Every JSP in the application is compiled by container and converted to Servlet and then container manages them like other servlets.
  • Miscellaneous Task – Web container manages the resource pool, does memory optimizations, run garbage collector, provides security configurations, support for multiple applications, hot deployment and several other tasks behind the scene that makes our life easier.

Web Application Directory Structure

Java Web Applications are packaged as Web Archive (WAR) and it has a defined structure. You can export above dynamic web project as WAR file and unzip it to check the hierarchy. It will be something like below image.

WAR-directory-structure

Deployment Descriptor

web.xml file is the deployment descriptor of the web application and contains mapping for servlets (prior to 3.0), welcome pages, security configurations, session timeout settings etc.

Thats all for the java web application startup tutorial, we will explore Servlets and JSPs more in future posts.

Update: Next tutorial in this series is Java Servlets Tutorial

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Current ye@r *

Subscribe to JournalDev Newsletter
Get the FREE access to Monthly Newsletter and Free PDF eBooks
*No Spam Guaranteed. By entering your email address, you agree also subscribing to our newsletter.
Oops! - Something went wrong.
Close
SSL Begineers Guide eBook Free Download Now
Exclusive Offer: Citrix™ Whitepaper on Denial of Service Attack Download Now