You are on page 1of 19

Learn Java for Web Development: Modern Java Web Development

By: Vishal Layka


Work: architecture, design, and implementation of distributed business systems.
service-oriented architecture, enterprise application architecture and development.
Learning the Java programming language is a noble cause, but learning merely the
Java language is not enough in the real world.
Java developers have to learn Java , a collection of related server-side
technologies, to put their Java skills to any real use.
But learning Java is not enough either. !he Java language along with Java
may suffice to develop web applications for pro"ects in the same organi#ation, as a
means to reusability, but the diverse landscape of Java on the Web is
permeated with several web frameworks, such as Spring Web MVC, that make
development much easier$ thus, a Java web developer has to have the knowledge of
these web frameworks.
%odern Java &eveloper.
%odern Java is more than "ust a language$ it is now a fully optimi#ed platform
because several other languages such as 'roovy and (cala, called the JVM
languages, now run on the Java Virtual %achine )JV%*.
+ll such JV% languages, especially 'roovy, have a close association with Java, and
you will come across web applications before long where Java and these other JV%
languages work in tandem. !he most ambitious pro"ects will re,uire you to build
web applications using these JV% languages.
-hat we are going to learn is, the specifics of Java on the -eb.
-eb .rameworks:
/ types
0. 1e,uest based 2 (tricts 3, (pring %V4
3. 4omponent based 2 J(. 3
5. 1apid - 'rails
/. 1eactive
&ifferent .rameworks: five frameworks )6*
(tructs 3, (pring -eb %V4, J(. 3, 'rails 3, 7lay 3 )using (cala*
%odern Java -eb +pplications: 5 players
0. JV% Languages
3. Java
5. Java -eb .rameworks.
8ntroducing Java -eb &evelopment
!he JV%, originally intended for Java, can now host a myriad of programming
languages, including 'roovy and (cala.
!he open source community has capitali#ed on capabilities offered by the languages
that run on the JV%, by means of web frameworks, to dramatically enhance the
productivity in web development and led to a renaissance of Java web development.
!his carves out a number of niches in the Java ecosystem, resulting in a richer
web landscape than ever before.
!he JV% languages represent a new category of languages that run on the JV%.
-ith the latest version, Java 9, Java is no longer a privileged JV% language and is
now simply one of the many languages that run on the JV%.
JV% Languages:
!he JV% is the runtime environment that provides you the ability to use different
programming languages for building web applications.
3 types:
0. Languages designed for the JV% 2 Java, 'roovy, (cala, 4lo"ure, etc
3. Languages ported to JV% 2 Jruby, Jphython, etc
'roovy 2 &ynamically typed language, can be used as a scripting language for the
Java platform, dynamically compiled to Java bytecode, and interoperates with other
Java code and libraries. 8t: synta; is similar to Java, but more fle;ible.
Java 2 (tatically typed language, imperative programming.
(cala 2 full support of functional programming, and a very strong statically typed
language. (cale code compiled to byte code to run on JV%.
4lo"ure 2 purely functional programming language, non-<< language.
<rder of functional programming language support:
Java 9 -= 'roovy 3 -= (cala -= 4lo"ure
Java
Java began life as a normal programming language for building standalone apps.
But soon, it has grown into other areas as well.
Lot of popularity 2 because its usage in creating web applications.
-eb applicaiton
0. (tatic web pages
3. &ynamic)8nteractive* web pages
(tatic web pages 2 uses >!%L?@>!%L, media)images, etcA to provide information.
&ynamic web pages 2 generating content with help of web components.
-eb +pplication 2 collection of web pages and is capable of generating dynamic
content in response to re,uests.
-eb 7age 2 to provide some information.
-eb +pplication 2 to perform an activity and save the result.
&eveloping -eb +pplication:
0. Java 2 set of +78s that are building blocks of web application.
3. -eb 4ontainer 2 implements +78 specs of Java . 7rovides services for
hosting, managing and e;ecuting web components
5. -eb 4omponents - >osted by the web container. ;amples, servlets, J(7s,
filters, and listeners, etc.
Java platform :
3 goals
0. 7roviding +78 specifications for web applications
3. (tandardi#ing and reducing the comple;ity of enterprise app development.
Java provides an application model that defines architecture for implementing
services.
!ypical +pplication %odel:
4lient !ier:
0. 4onsists of application clients that makes re,uests to the Java server.
3. <ften located on a different machine.
5. !he server processes the re,uests and returns a response to the client.
/. ;ample: web browser, etc.
-eb !ier:
>andles interaction between clients and the business tier.
0. 4ollects input from the client
3. 4ontrols the flow of screens or pages on the client
5. %aintains the state of data for a user:s session
/. <btains results from the components in the business tier
6. 'enerates dynamic content in various formats to the client
-henver developing an enterprise application, think of these system services, like
logging, transaction, and security.
+ generali#ed view of layers in an enterprise application:
-eb Layer:
0. !he web layer of a web application consists of the web tier components of
Java such as servlets and J(7.
3. !he web layer can access the service layer, but there should not be a tight
coupling between the web layer and the service layer.
7lease understand, no tight coupling between web layer and service layer.
4hanging service layer should not impact web layer.
(ervice Layer:
0. !he service layer consists of the business tier components of Java such as
nterprise JavaBeans )JBs*.
3. !he service layer can access the data access layer, but no tight coupling
between service layer and data access layer.
7lease understand, in fact, the service layer should not know anything about the
web or data access layer.
!he service layer provides a coarse-grained interface for the web layer.
&ata +ccess Layer:
0. !he data access layer consists of the data tier components of Java such as
J&B4 and J7+.
3. !his layer should not contain any business logic.
7lease understand, this layer abstracts the actual persistence mechanism )in other
words, J&B4 or J7+* from the service layer by providing the coarse-grained interface
to the service layer.
Java -eb .rameworks
-hy going with web framework, inspite of Java providing an application model,
and providing components ade,uate to develop web applicationsBBB
3 problems:
0. 8nteracting directly with Java components results in lot of boilerplate code
and even code redundancy.
3. 8t:s not a non-trivial task and all team members many not have the level of
e;pertise that meets the Java criteria.
6 frameworks which we are going to learn:
(truct 3, (pring %V4, J(. 3, 'rails 3)Csing 'roovy*, 7lay 3 )Csing (cala*
(imple +pplication 2 Book (tore application
+ simple data model that will be used for the bookstore web application.
0. !he 4ategory table stores the different categories of books$ categories include
Java, (cala, and so on.
3. !he Book table stores the book details such as titles.
5. !he +uthor table stores the details of the authors.
ach category can have #ero or more books. 8n other words, there is a one-to-many
relationship between the 4ategory and Book tables.
ach book can have one or more authors. 8n other words, there is a one-to-many
relationship between the Book and +uthor tables.
-e are going to use %y(DL for our applicaiton.
!o create the books database, use the following command:
create database books;
Eou need to instruct %y(DL to create tables in the books database by using the
following command:
use books;
CREATE TABLE CATEGORY (
ID INT NOT NULL AUTO_INCREMENT ,
CATEGORY_DECRI!TION "ARC#AR($%& NOT NULL ,
!RIMARY 'EY (ID&
&;
CREATE TABLE BOO' (
ID INT NOT NULL AUTO_INCREMENT,
CATEGORY_ID INT NOT NULL ,
BOO'_TITLE "ARC#AR((%& NOT NULL,
!UBLI#ER "ARC#AR((%& NOT NULL ,
!RIMARY 'EY (ID& ,
CONTRAINT )'_BOO'_* )OREIGN 'EY (CATEGORY_ID& RE)ERENCE
CATEGORY(ID&

&;
CREATE TABLE AUT#OR (
ID INT NOT NULL AUTO_INCREMENT ,
BOO'_ID INT NOT NULL ,
)IRT_NAME "ARC#AR($%& NOT NULL ,
LAT_NAME "ARC#AR($%& NOT NULL ,
!RIMARY 'EY (ID& ,
CONTRAINT )'_AUT#OR_* )OREIGN 'EY (BOO'_ID& RE)ERENCE BOO' (ID&
&;
Fow populate the tables using the +,sert statements, as follows:
+,sert +,to cate-or. (cate-or._descr+/t+o,& 0a1ues (2C1o3ure2&;
+,sert +,to cate-or. (cate-or._descr+/t+o,& 0a1ues (2Groo0.2&;
+,sert +,to cate-or. (cate-or._descr+/t+o,& 0a1ues (24a0a2&;
+,sert +,to cate-or. (cate-or._descr+/t+o,& 0a1ues (2ca1a2&;
+,sert +,to Book (CATEGORY_ID, BOO'_TITLE, !UBLI#ER& 0a1ues (*,
2!ract+ca1 C1o3ure2, 2A/ress2&;
+,sert +,to Book (CATEGORY_ID, BOO'_TITLE, !UBLI#ER& 0a1ues ($,
2Be-+,,+,- Groo0., Gra+1s a,d Gr+55o,2, 2A/ress2&;
+,sert +,to Book (CATEGORY_ID, BOO'_TITLE, !UBLI#ER& 0a1ues ($,
2De5+,+t+0e Gu+de to Gra+1s $2, 2A/ress2&;
+,sert +,to Book (CATEGORY_ID, BOO'_TITLE, !UBLI#ER& 0a1ues ($,
2Groo0. a,d Gra+1s Rec+/es2, 2A/ress2&;
+,sert +,to Book (CATEGORY_ID, BOO'_TITLE, !UBLI#ER& 0a1ues (6,
2Moder, 4a0a 7eb De0e1o/8e,t2, 2A/ress2&;
+,sert +,to Book (CATEGORY_ID, BOO'_TITLE, !UBLI#ER& 0a1ues (6, 24a0a
9 Rec+/es2, 2A/ress2&;
+,sert +,to Book (CATEGORY_ID, BOO'_TITLE, !UBLI#ER& 0a1ues (6, 24a0a
EE 9 Rec+/es2, 2A/ress2&;
+,sert +,to Book (CATEGORY_ID, BOO'_TITLE, !UBLI#ER& 0a1ues (6,
2Be-+,,+,- 4a0a 9 2, 2A/ress2&;
+,sert +,to Book (CATEGORY_ID, BOO'_TITLE, !UBLI#ER& 0a1ues (6, 2!ro
4a0a 9 NIO:$2, 2A/ress2&;
+,sert +,to Book (CATEGORY_ID, BOO'_TITLE, !UBLI#ER& 0a1ues (6, 24a0a
9 5or Abso1ute Be-+,,ers2, 2A/ress2&;
+,sert +,to Book (CATEGORY_ID, BOO'_TITLE, !UBLI#ER& 0a1ues (6,
2Orac1e Cert+5+ed 4a0a E,ter/r+se Arc;+tect 4a0a EE92, 2A/ress2&;
+,sert +,to Book (CATEGORY_ID, BOO'_TITLE, !UBLI#ER& 0a1ues (<,
2Be-+,,+,- ca1a2, 2A/ress2&;
+,sert +,to Aut;or (BOO'_ID, )IRT_NAME, LAT_NAME& 0a1ues (*, 2Luke2,
2"a,der#art2&;
+,sert +,to Aut;or (BOO'_ID, )IRT_NAME, LAT_NAME& 0a1ues ($,
2"+s;a12, 2La.ka2&;
+,sert +,to Aut;or (BOO'_ID, )IRT_NAME, LAT_NAME& 0a1ues (6, 24e552,
2Bro=,2&;
+,sert +,to Aut;or (BOO'_ID, )IRT_NAME, LAT_NAME& 0a1ues (<,
2Bas;ar2, 24a=ad2&;
+,sert +,to Aut;or (BOO'_ID, )IRT_NAME, LAT_NAME& 0a1ues (>,
2"+s;a12, 2La.ka2&;
+,sert +,to Aut;or (BOO'_ID, )IRT_NAME, LAT_NAME& 0a1ues ((,
24os;2, 24u,eau2&;
+,sert +,to Aut;or (BOO'_ID, )IRT_NAME, LAT_NAME& 0a1ues (9, 24os;2,
24u,eau2&;
+,sert +,to Aut;or (BOO'_ID, )IRT_NAME, LAT_NAME& 0a1ues (?, 24e552,
2)r+ese,2&;
+,sert +,to Aut;or (BOO'_ID, )IRT_NAME, LAT_NAME& 0a1ues (@,
2A,-;e12, 2Leo,ard2&;
+,sert +,to Aut;or (BOO'_ID, )IRT_NAME, LAT_NAME& 0a1ues (*%,
24a.2, 2Br.a,t2&;
+,sert +,to Aut;or (BOO'_ID, )IRT_NAME, LAT_NAME& 0a1ues (**, 2B "2,
2'u8ar2&;
+,sert +,to Aut;or (BOO'_ID, )IRT_NAME, LAT_NAME& 0a1ues (*$,
2Da0+d2, 2!o11ak2&;
&ata +ccess Layer for the Bookstore +pplication:
Fow that the database is ready, you will build the data access layer for application.
!he data access layer is responsible for interfacing with the underlying persistence
mechanism in a transparent way in order to store and retrieve ob"ects from the
database.
!his transparency means that the data access layer can switch the persistence
mechanism from plain J&B4 to <1% persistence technologies such as >ibernate,

J7+, and so on, without affecting the client of the data access layer.
!his transparency is achieved via the data access ob"ect )&+<* pattern.
!he DAO ob"ect provides an interface to the database or the underlying persistence
mechanism, thus abstracting the underlying implementation from the client.
!he data access layer will retrieve the data via J&B4 from the database and directly
map the result set into Java ob"ects. !hese Java ob"ects are the domain ob"ects in
the application that are the Java representation of the tables in the database.
!he &+< maps application calls to the persistence mechanism and provides specific
data operations without e;posing details of the database. !he &+< interface
abstracts the implementation details of accessing the data from the client
)application ob"ect* and provides the domain-specific ob"ects that the client
)application ob"ect* needs.
.irst (tep:
.irst, you need to create the domain-specific classes for the Java <b"ect
representations of the database tables.
(ample 4ode:
package com.apress.books.model;
public class Category {
private Long id;
private String categoryDescription;

public Long getId() {
return id;
}

public void setId(Long id) {
this.id= id;
}

public String getCategoryDescription() {
return categoryDescription;
}

public void setCategoryDescription(String categoryDescription) {
this.categoryDescription = categoryDescription;
}

public String toString() {
return "Category Id! " " id " "# Category Description! "
" categoryDescription;
}
}
package com.apress.books.model;
import $a%a.&til.List;
import com.apress.books.model.'&t(or;
public class )ook {
private Long id;
private Long categoryId;
private String book*itle;
private List+'&t(or, a&t(ors;
private String p&blis(er-ame;

public Long getId() {
return id;
}

public void setId(Long id) {
this.id= id;
}

public Long getCategoryId() {
return categoryId;
}

public void setCategoryId(Long categoryId) {
this.categoryId = categoryId;
}

public String get)ook*itle() {
return book*itle;
}

public void set)ook*itle(String book*itle) {
this.book*itle = book*itle;
}

public List+'&t(or, get'&t(ors() {
return a&t(ors;
}

public void set'&t(ors(List+'&t(or, a&t(ors) {
this.a&t(ors = a&t(ors;
}

public String get.&blis(er-ame() {
return p&blis(er-ame;
}

public void set.&blis(er-ame(String p&blis(er-ame) {
this.p&blis(er-ame = p&blis(er-ame;
}

public String toString() {
return ")ook Id! " " id " "# )ook *itle! " " book*itle;
}
}
package com.apress.books.model;
public class '&t(or {
private Long id;
private Long bookId;
private String /irst-ame;
private String last-ame;

public Long getId() {
return id;
}

public void setId(Long id) {
this.id= id;
}

public Long get)ookId() {
return bookId;
}

public void set)ookId(Long bookId) {
this.bookId = bookId;
}

public String get0irst-ame() {
return /irst-ame;
}

public void set0irst-ame(String /irst-ame) {
this./irst-ame = /irst-ame;
}

public String getLast-ame() {
return last-ame;
}

public void setLast-ame(String last-ame) {
this.last-ame = last-ame;
}

public String toString() {
return "'&t(or Id! " " id " "# )ook id! " " bookId " "# 0irst -ame! "
" /irst-ame " "# Last -ame! " "last-ame;
}
}
package com.apress.books.dao;
import $a%a.&til.List;
import com.apress.books.model.)ook;
import com.apress.books.model.Category;
public interface )ookD'1 {
public List+)ook,/ind'll)ooks();
public List+)ook,searc()ooks)y2ey3ord(String key4ord);
public List+Category,/ind'llCategories();
public void insert()ook book);
public void &pdate()ook book);
public void delete(Long bookId);
}
package com.apress.books.dao;
import $a%a.s5l.Connection;
import $a%a.s5l.Dri%er6anager;
import $a%a.s5l..reparedStatement;
import $a%a.s5l.7es&ltSet;
import $a%a.s5l.S8L9:ception;
import $a%a.&til.'rrayList;
import $a%a.&til.List;
import com.apress.books.model.'&t(or;
import com.apress.books.model.)ook;
import com.apress.books.model.Category;
public class )ookD'1Impl implements )ookD'1 {
static {
try {
Class.forName("com.mys5l.$dbc.Dri%er");
}
catch (Class-ot0o&nd9:ception e:) {
}
}
private Connection getConnection() throws S8L9:ception {
return Dri%er6anager.getConnection("$dbc!mys5l!;;local(ost;books"#
"rag(&"# "c(ot&<=>");
}
private void closeConnection(Connection connection) {
if (connection == null)
return;
try {
connection.close();
}
catch (S8L9:ception e:) {
}
}
public List+)ook, /ind'll)ooks() {
List+)ook, res&lt = new 'rrayList+,();
List+'&t(or, a&t(orList = new 'rrayList+,();
String s5l = "select ? /rom book inner $oin a&t(or on book.id=
a&t(or.book@id";
Connection connection = null;
try {
connection = getConnection();
.reparedStatement statement =
connection.prepareStatement(s5l);
7es&ltSet res&ltSet = statement.e:ec&te8&ery();
while (res&ltSet.ne:t()) {
)ook book = new )ook();
'&t(or a&t(or = new '&t(or();
book.setId(res&ltSet.getLong("id"));
book.set)ook*itle(res&ltSet.getString("book@title"));
book.setCategoryId(res&ltSet.getLong("category@id"));
a&t(or.set)ookId(res&ltSet.getLong("book@Id"));
a&t(or.set0irst-ame(res&ltSet.getString("/irst@name"));
a&t(or.setLast-ame(res&ltSet.getString("last@name"));
a&t(orList.add(a&t(or);
book.set'&t(ors(a&t(orList);
book.set.&blis(er-ame(res&ltSet.getString("p&blis(er"));
res&lt.add(book);
}
} catch (S8L9:ception e:) {
e:.printStack*race();
} finally {
closeConnection(connection);
}
return res&lt;
}
public List+)ook, searc()ooks)y2ey3ord(String key4ord) {
List+)ook, res&lt = new 'rrayList+,();
List+'&t(or, a&t(orList = new 'rrayList+,();
String s5l = "select ? /rom book inner $oin a&t(or on book.id=
a&t(or.book@id"
" " 3(ere book@title like AB"
" key4ord.trim()
" "BA"
" " or /irst@name like AB"
" key4ord.trim()
" "BA"
" " or last@name like AB" " key4ord.trim() " "BA";
Connection connection = null;
try {
connection = getConnection();
.reparedStatement statement =
connection.prepareStatement(s5l);
7es&ltSet res&ltSet = statement.e:ec&te8&ery();
while (res&ltSet.ne:t()) {
)ook book = new )ook();
'&t(or a&t(or = new '&t(or();
book.setId(res&ltSet.getLong("id"));
book.set)ook*itle(res&ltSet.getString("book@title"));
book.set.&blis(er-ame(res&ltSet.getString("p&blis(er"));
a&t(or.set0irst-ame(res&ltSet.getString("/irst@name"));
a&t(or.setLast-ame(res&ltSet.getString("last@name"));
a&t(or.set)ookId(res&ltSet.getLong("book@id"));
a&t(orList.add(a&t(or);
book.set'&t(ors(a&t(orList);
res&lt.add(book);
}
} catch (S8L9:ception e:) {
e:.printStack*race();
} finally {
closeConnection(connection);
}
return res&lt;
}
public List+Category, /ind'llCategories() {
List+Category, res&lt = new 'rrayList+,();
String s5l = "select ? /rom category";
Connection connection = null;
try {
connection = getConnection();
.reparedStatement statement =
connection.prepareStatement(s5l);
7es&ltSet res&ltSet = statement.e:ec&te8&ery();
while (res&ltSet.ne:t()) {
Category category = new Category();
category.setId(res&ltSet.getLong("id"));
category.setCategoryDescription(res&ltSet.getString("category@description"));
res&lt.add(category);
}
} catch (S8L9:ception e:) {
e:.printStack*race();
} finally {
closeConnection(connection);
}
return res&lt;
}
public void insert()ook book) {
}
public void &pdate()ook book) {
}
public void delete(Long bookId) {
}
}
%ain +pplication:
package com.apress.books.client;
import $a%a.&til.List;
import com.apress.books.dao.)ookD'1;
import com.apress.books.dao.)ookD'1Impl;
import com.apress.books.model.)ook;
public class )ook'pp {
private static )ookD'1 bookDao = new )ookD'1Impl();
public static void main(StringCD args) {
;; List all books
System.err.println("Listing all )ooks!");
findAllBooks();
System.out.println();
;; searc( book by key3ord
System.err.println("Searc( book by key3ord in book title !
Eroo%y!");
searchBooks("Eroo%y");
System.out.println();
System.err.println("Searc( book by key3ord in a&t(orAs name !
Fos(!");
searchBooks("Fos(");
}
private static void /ind'll)ooks() {
List+)ook, books = bookDao./ind'll)ooks();
for ()ook book ! books) {
System.out.println(book);
}
}
private static void searc()ooks(String key4ord) {
List+)ook, books = bookDao.searc()ooks)y2ey3ord(key4ord);
for ()ook book ! books) {
System.out.println(book);
}
}
}
!rends and !echnologies in Java -eb Landscape:
1apid web development frameworks: 'rails 3, 7lay 3.
4ross-browser compatibility, grown even with advent of smart phones.
-eb +pplications are e;pected to run on smarphones as well as desktops.
4reating separate web applications for the desktop and the smartphones has
significant overhead as well as maintenance. --= 1esponsive -eb &esign
1esponsive web applications are device-agnostic. !hey adapt themselves to the
devices on which they are run.
Eou can go one step further by designing the web application with the smallest
screen )smartphones* in mind and then progressively enhance the application to run
on desktop screens. !his techni,ue is known as mobile-first design.
!he core technologies employed in developing responsive web applications are
4((5, "Duery and "Duery plug-ins,

L((, 4offee(cript, and front-end frameworks
such as Bootstrap, 7olyfills, and %oderni#r.
Unobtrusive JavaScript
3/
: Unobtrusive JavaScript is a means of separation of concerns, that
is, separating the look and feel from behavior concerns. This results in a pure markup, and
the JavaScript (behavior) works unobtrusivel across different browsers and devices. !"uer
is a popular librar that helps in writing unobtrusive JavaScript. #offeeScript compiles into
JavaScript. $t is used as an alternative to JavaScript and considerabl reduces code.
CSS3 media queries: %edia ,ueries are the primary means of making web
applications responsive. %edia ,ueries use media features such as device-
width, device-height, orientation, and device-aspect-ratio in a 4(( file to
develop a responsive web application.
LESS: L(( is the 4(( preprocessor that is used when a 4((5 stylesheet
gets unmanageable. L(( e;tends 4(( with dynamic behavior such as mi;ins
and functions.
Polyfills: 7olyfills are Java(cript, used to make a browser >!%L6-enabled.
!he polyfills provide missing functionality in the browser and provide a
fallback.
Modernizr: %oderni#r is a Java(cript library that detects >!%L6 and 4((5
features in the browser and conditionally loads polyfills.
(ingle 7age -eb +pplication )(7+* :
!he client-side codeGsuch as >!%L, Java(cript, and 4((Gis retrieved with a
single page load$ the page does not reload at any point in the process, and
the control is not transferred to another page.
!he resources, such as images, are dynamically loaded and added to the
page in response to events.
(7+s are built using Fode."s

as the web server. +ngularJ( is a full-featured (7+
framework.
1eal-!ime -eb +pplications:
+ real-time web application delivers responses to events in a measurable and
acceptable time period, depending on the nature of the event, by means of
asynchronous, bidirectional communication between the client and the server.
-eb(ocket is the core technology employed for developing real-time web
applications.
-eb(ocket provides a full-duple; and bidirectional communication protocol
over a single !47 connection.
!hat is, a client and a server can send messages to each other and
independent of each other.
+ few e;amples of the applications that re,uire real-time functionality are chat
applications, multiplayer online games, stock trading applications, and so on.
Building -eb +pplications Csing (ervlets and J(7:
!he 8nternet is a colossal network of networks. +ll of machines on the 8nternet can
be classified into two types: server and client.
4lient 2 re,uesting some information.
(erver 2 provides that information.
8nformation provider 2 (erver
8nformation re,uester 2 4lient
7rotocol 2 governs marshalling of data to be transmitted by the (erver and Cn-
marshalling of data to be translated or read by the client.
!he protocol is >!!7. -eb browser)client*, -eb server)server* and web application
all converse with each other using >!!7 protocol.
>!!7 1e,uests and >!!7 1esponses.
>!!7 is a re,uest-response stateless protocol. -eb server:s view, any re,uest is the
first re,uest from the web browser.
C1L 2 Cniform 1esource Locator 2 uniform way of uni,uely identifying a resource.
H---= locating a resource by describing its :location: on a network.
+ generic C1L is a hierarchical se,uence of components, structured as
scheme:??hostFame:portFumber?path?resourceB,ueryIstring.
(cheme : http ? https
!he host name and port number together are termed an authority.
>ttp 2 default port 9A
https 2 default port //5
!omcat web server listens for incoming re,uests on port 9A9A.
-hen present, a ,uery string is a series of name-value pairs preceded with a
,uestion mark )B* and with an ampersand )J* separating the pairs.
Duery strings are supported only for the '! method.
+ web application is a collection of web components that work together. 8n Java ,
a web component is either a (ervlet or a J(7.
-eb components are managed and e;ecuted inside the web container, also called a
servlet container, which provides additional features such as security.
-eb server forwards re,uest to the servlet container in which web component
resides.
-eb browser -= web server -= servlet container -= servlet
+ll re,uests for the dynamic content are mediated by the servlet container.
+ (ervlet is a "ava class that acts as a dynamic web resource.
(ervlets
(ervlets are responsible for most of the processing re,uired by a web application.
+ servlet is a "ava class that implements "ava;.servlet.(ervlet interface. !he (ervlet
interface defines the methods that all servlets must implement.
Life cycle methods:
init)* - to initiali#e a servlet
service)* - to service re,uests
destroy)* - to remove a servlet from the server
void init(Servlet#onfig config)
void service(Servlet%e&uest re&, Servlet%esponse res)
void 'estro()
init(Servlet#onfig): #alled b the servlet container exactly once after instantiating the
servlet. This method must complete successfull before the servlet is a candidate to receive
an re&uests.
service(): #alled b the servlet container, after the servlet(s init() method has completed
successfull, to allow the servlet to respond to a re&uest.
destro(): #alled b the container to destro the servlet and serves as a method in which the
servlet must release ac&uired resources before it is destroed.
getServlet#onfig(): )llows the servlet to get start*up information in the form of a
Servlet#onfig ob!ect returned b this method. The Servlet#onfig ob!ect contains
initiali+ation and start*up parameters for the servlet.
getServlet$nfo(): )llows the servlet to return its own information such as the servlet(s author
and version.
1e,uest .low for the >ello-orld (ervlet
!he re,uest originating from the web browser flows through the web server and the
servlet container before the >ello-orld servlet can generate the response.
-eb browser -= web server -= servlet container -= your servlet
>!!7 1e,uest %essage:
-hen user access the web application through this C1L, web browser creates >!!7
1e,uest.
'! ?helloworld?hello >!!7?0.0
>ost: localhost:9A9A
Cser-+gent: %o#illa?6.A )-indows F! K.0* +pple-ebLit?65M.50 )L>!%L, like 'ecko*
4hrome?3K.A.0/0A./5 (afari?65M.50
web browser -= re,uest )say '! re,uest* -= web server -= sees the resource path
in re,uest.
8f the resource re,uested by the user is not a static page, so forwards re,uest to
web container.
!omcat is both web server N web container.
1esource path in C1L to (ervlet mapping is through web.;ml file. )&eployment
&escriptor file*
!he Oservlet= tag is used to configure our servlet. 8t contains two nested tags:
Oservlet-name= defines a logical name for the servlet, and Oservlet-class=
indicates the Java class defining the servlet.
Oservlet=
Oservlet-name=
Oservlet-class=
O?servlet=
!he Oservlet-mapping= @%L tag is used to configure our servlet. 8t contains two
nested tags: Oservlet-name= matches the value set in the Oservlet= tag, and Ourl-
pattern= sets the C1L pattern for which the servlet will e;ecute.
Oservlet-mapping=
Oservlet-name=
Ourl-pattern=
O?servlet-mapping=
one instance of servlet per JV%
one JV% 2 one servlet instance only.
Java web applications run from within a conte;t root.
!he conte;t root is the first string in the C1L after the server name and port.
!he value for Ourl-pattern= is relative to the applicationPs conte;t root.
!he web container loads the servlet class and instantiates it. very client re,uest
generates a new pair of re,uest and response ob"ects.
!he web container runs multiple threads to process multiple re,uests to a single
instance of the servlet.
+ servlet has to e;ecute inside the web container.
+n >!!7 re,uest to an >ttp(ervlet subclass goes through a number of steps:
,. ) call to the public service (Servlet%e&uest, Servlet%esponse) method b the container.
-. 'elegation of this call to .ttpServlet(s protected service (.ttpServlet%e&uest,
.ttpServlet%esponse) method.
/. The protected service (.ttpServlet%e&uest, .ttpServlet%esponse) method then delegates to
the appropriate do011 method, depending on the .TT2 method used for the re&uest.
!he 'eneric(ervlet abstract class defines an init)* method that is called by the
default init)(ervlet4onfig* method to e;ecute any application-specific servlet
initiali#ation.
!he service)* method is implemented by >ttp(ervlet, which inspects the incoming
>!!7 method and invokes the appropriate method for that re,uest type.
!he init)(ervlet4onfig* method calls the no-arg init)*, so you need to override only
the no-arg version.
init) *
!he container calls init)*on the servlet instance. Eou can override it in order to get
database connections registered with other ob"ects. <therwise, the init)* method
from the 'enericservlet runs.
!he web container calls the init)* method of the servlet )only once in the servletPs
life*, and the init)* method must complete before the container can call service)*
method.
service) *
!he container calls the service)* method of the servlet. !his method looks at the
re,uest, determines the type of >!!7 method, and invokes the matching do'et)* or
do7ost)* on the servlet. Eou never override it. Eour "ob is to override do'et)* or
do7ost)*.
destroy) *
!he servlet container calls the destroy)* method on the servlet, and this method is
called only once. !his method provides the servlet with an opportunity to release
ac,uired resources before it is destroyed.

You might also like