0% found this document useful (0 votes)
154 views41 pages

Unit 4 1 FSD Cse

Uploaded by

Bhagya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
154 views41 pages

Unit 4 1 FSD Cse

Uploaded by

Bhagya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

UNIT – IV

Java Web Development: JAVA PROGRAMMING BASICS, Model View Controller (MVC) Pattern MVC
Architecture using Spring RESTful API using Spring Framework Building an application using Maven

JAVA PROGRAMMING BASICS


JAVA – BASICS
1. Java – Overview
History of Java
Tools You Will Need
Try It Option
What is Next?
2. Java - Environment Setup
Try it Option Online
Local Environment Setup
Popular Java Editors
What is Next?
3. Java – Basic Syntax
First Java Program
Basic Syntax
Java Identifiers
Java Modifiers
Java Variables
Java Arrays
Java Enums
Java Keywords
Comments in Java
Using Blank Lines
Inheritance
Interfaces
What is Next?
4. Java – Objects & Classes
Objects in Java
Classes in Java
Constructors
How to Use Singleton Class?
Creating an Object
Accessing Instance Variables and Methods
Source File Declaration Rules
Java Package
Import Statements
A Simple Case Study
What is Next?

5. Java – Basic Datatypes


Primitive Datatypes
Reference Datatypes
Java Literals
What is Next?
6. Java – Variable Types
Local Variables
Instance Variables
Class/static Variables
What is Next?
7. Java – Modifier Types
8. Java Access Modifiers
Java Non-Access Modifier
The Static Modifier
The Final Modifier
The Abstract Modifier
Access Control Modifiers
Non-Access Modifiers
What is Next?
9. Java – Basic Operators
The Arithmetic Operators
The Relational Operators
The Bitwise Operators
The Logical Operators
The Assignment Operators
Miscellaneous Operators
Precedence of Java Operators
What is Next?
10. Java – Loop Control
While Loop in Java
for Loop in Java
Do While Loop in Java
Loop Control Statements
Break Statement in Java
Continue Statement in Java
Enhanced for loop in Java
What is Next?
11. Java – Decision Making
If Statement in Java
If-else Statement in Java
The if...else if...else Statement
Nested if Statement in Java
Switch Statement in Java
The ? : Operator:
What is Next?

12. Java – Numbers Class


Number Methods
Java XXXValue Method
Java – compareTo() Method
Java – equals() Method
Java – valueOf() Method
Java – toString() Method
Java – parseInt() Method
Java – abs() Method
Java – ceil() Method
Java – floor() Method
Java – rint() Method
Java – round() Method
Java – min() Method
Java – max() Method
Java – exp() Method
Java – log() Method
Java – pow() Method
Java – sqrt() Method
Java – sin() Method
Java – cos() Method
Java – tan() Method
Java – asin() Method
Java – acos() Method
Java – atan() Method
Java – atan2() Method
Java – toDegrees() Method
Java – toRadians() Method
Java – random() Method
What is Next?
13. Java – Character Class
Escape Sequences
Character Methods
Java – isLetter() Method
Java – isDigit() Method
Java – isWhitespace() Method
Java – isUpperCase() Method
Java – isLowerCase() Method
Java – toUpperCase() Method
Java – toLowerCase() Method
Java – toString() Method
What is Next?
14. Java – Strings Class
Creating Strings
Java – String Buffer & String Builder Classes
StringBuffer Methods
Java – String Buffer append() Method
Java – String Buffer reverse() Method

Java – String Buffer delete() Method


Java – String Buffer insert() Method
Java – String Buffer replace() Method
String Length
Concatenating Strings
Creating Format Strings
String Methods
Java – String chartAt() Method
Java – String compareTo(Object o) Method
Java – String compareTo(String anotherString) Method
Java – String compareToIgnoreCase() Method
Java – String concat() Method
Java – String contentEquals() Method
Java – String copyValueOf(char[] data) Method
Java – String copyValueOf(char[] data, int offset, int count) Method
Java – String endsWith() Method
Java – String equals() Method
Java – String equalsIgnoreCase() Method
Java – String getBytes(String charsetName) Method
Java – String getBytes() Method
Java – String getChars() Method
Java – String hashCode() Method
Java – String indexOf(int ch) Method
Java – String indexOf(int ch, int fromIndex) Method
Java – String indexOf(String str) Method
Java – String indexOf(String str, int fromIndex) Method
Java – String Intern() Method
Java – String lastIndexOf(int ch) Method
Java – String lastIndexOf(int ch, int fromIndex) Method
Java – String lastIndexOf(String str) Method
Java – String lastIndexOf(String str, int fromIndex) Method
Java – String length() Method
Java – String matches() Method
Java – String regionMatches() Method
Java – String regionMatches() Method
Java – String replace() Method
Java – String replaceAll() Method
Java – String replaceFirst() Method
Java – String split() Method
Java – String split() Method
Java – String startsWith() Method
Java – String startsWith() Method
Java – String subsequence() Method
Java – String substring() Method
Java – String substring() Method
Java – String toCharArray() Method
Java – String toLowerCase() Method
Java – String toLowerCase() Method
Java – String toString() Method
Java – String toUpperCase() Method
Java – String toUpperCase() Method
Java – String trim() Method
Java – String valueOf() Method
15. Java – Arrays
Declaring Array Variables
Creating Arrays
Processing Arrays
The foreach Loops
Passing Arrays to Methods
Returning an Array from a Method
The Arrays Class
16. Java – Date & Time
Getting Current Date & Time
Date Comparison
Simple DateFormat Format Codes
Date and Time Conversion Characters
Parsing Strings into Dates
Sleeping for a While
Measuring Elapsed Time
GregorianCalendar Class
17. Java – Regular Expressions
Capturing Groups
Regular Expression Syntax
Methods of the Matcher Class
18. Java – Methods
Creating Method
Method Calling
The void Keyword
Passing Parameters by Value
Method Overloading
Using Command-Line Arguments
The Constructors
Parameterized Constructor
The this keyword
Variable Arguments(var-args)
The finalize( ) Method
19. Java – Files and I/O
20. Stream
Standard Streams
Reading and Writing Files
ByteArrayInputStream
DataInputStream
FileOutputStream
ByteArrayOutputStream
DataOutputStream
File Navigation and I/O
File Class
Directories in Java
Listing Directories
21. Java – Exceptions
Exception Hierarchy
Built-in Exceptions
Exceptions Methods
Catching Exceptions
Multiple Catch Blocks
Catching Multiple Type of Exceptions
The Throws/Throw Keywords
The Finally Block
The try-with-resources
User-defined Exceptions
Common Exceptions
22. Java – Inner Classes
Nested Classes
Inner Classes (Non-static Nested Classes)
Accessing the Private Members
Method-local Inner Class
Anonymous Inner Class
Anonymous Inner Class as Argument
Static Nested Class
JAVA - OBJECT ORIENTED
23. Java – Inheritance
extends Keyword
Sample Code
The super keyword
Invoking Superclass Constructor
IS-A Relationship
The instanceof Keyword
HAS-A relationship
Types of Inheritance
24. Java – Overriding
Rules for Method Overriding
Using the super Keyword
25. Java – Polymorphism
Virtual Methods
26. Java – Abstraction
Abstract Class
Inheriting the Abstract Class
Abstract Methods

27. Java – Encapsulation


Benefits of Encapsulation
28. Java – Interfaces
Declaring Interfaces
Implementing Interfaces
Extending Interfaces
Extending Multiple Interfaces
Tagging Interfaces
29. Java – Packages
Creating a Package
The import Keyword
The Directory Structure of Packages
Set CLASSPATH System Variable
JAVA – ADVANCED
30. Java – Data Structures
The Enumeration
The BitSet
The Vector
The Stack
The Dictionary
The Hashtable
The Properties
31. Java – Collections Framework
The Collection Interfaces
The Collection Interface
The List Interface
The Set Interface
The SortedSet Interface
The Map Interface
The Map.Entry Interface
The SortedMap Interface
The Enumeration Interface
The Collection Classes
The LinkedList Class
The ArrayList Class
The HashSet Class
The LinkedHashSet Class
The TreeSet Class
The HashMap Class
The TreeMap Class
The WeakHashMap Class
The LinkedHashMap Class
The IdentityHashMap Class
The Vector Class
The Stack Class
The Dictionary Class
The Map Interface
The Hashtable Class
The Properties Class
The BitSet Class
The Collection Algorithms
How to Use an Iterator ?
How to Use a Comparator ?
Summary
32. Java – Generics
Generic Methods
Bounded Type Parameters
Generic Classes
33. Java – Serialization
Serializing an Object
Deserializing an Object
34. Java – Networking
URL Processing
URL Class Methods
URLConnections Class Methods
Socket Programming
ServerSocket Class Methods
Socket Class Methods
InetAddress Class Methods
Socket Client Example
Socket Server Example
35. Java – Sending E-mail
Send a Simple E-mail
Send an HTML E-mail
Send Attachment in E-mail
User Authentication Part
36. Java – Multithreading
Life Cycle of a Thread
Thread Priorities
Create a Thread by Implementing a Runnable Interface
Create a Thread by Extending a Thread Class
Thread Methods
Major Java Multithreading Concepts
Thread Synchronization
Interthread Communication
Thread Deadlock
Thread Control
37. Java – Applet Basics
Life Cycle of an Applet
A "Hello, World" Applet
The Applet Class
Invoking an Applet
HTML <applet> Tag
HTML Attribute Reference
HTML Events Reference
Getting Applet Parameters
Specifying Applet Parameters
Application Conversion to Applets
Event Handling
Displaying Images
Playing Audio
38. Java – Documentation Comments
What is Javadoc?
The javadoc Tags
Java

1. Java-Overview

Java programming language was originally developed by Sun Microsystems which was initiated by James Gosling and
released in 1995 as core component of Sun Microsystems'Java platform (Java 1.0 [J2SE]).
The latest release of the Java Standard Edition is Java SE 8. With the advancement of Javaand its widespread popularity,
multiple configurations were built to suit various types of platforms. For example: J2EE for Enterprise Applications, J2ME
for Mobile Applications.
The new J2 versions were renamed as Java SE, Java EE, and Java ME respectively. Java is guaranteed to be Write Once,
Run Anywhere.
Java is:
 Object Oriented: In Java, everything is an Object. Java can be easily extended since it is based on the Object
model.

 Platform Independent: Unlike many other programming languages including Cand C++, when Java is compiled, it
is not compiled into platform specific machine,rather into platform independent byte code. This byte code is
distributed over theweb and interpreted by the Virtual Machine (JVM) on whichever platform it is beingrun on.

 Simple: Java is designed to be easy to learn. If you understand the basic conceptof OOP Java, it would be easy to
master.

 Secure: With Java's secure feature it enables to develop virus-free, tamper-free systems. Authentication techniques
are based on public-key encryption.

 Architecture-neutral: Java compiler generates an architecture-neutral object file format, which makes the
compiled code executable on many processors, withthe presence of Java runtime system.

 Portable: Being architecture-neutral and having no implementation dependent aspects of the specification makes
Java portable. Compiler in Java is written in ANSI C with a clean portability boundary, which is a POSIX subset.

 Robust: Java makes an effort to eliminate error prone situations by emphasizingmainly on compile time error
checking and runtime checking.

 Multithreaded: With Java's multithreaded feature it is possible to write programsthat can perform many tasks
simultaneously. This design feature allows the developers to construct interactive applications that can run
smoothly.

 Interpreted: Java byte code is translated on the fly to native machine instructions and is not stored anywhere. The
development process is more rapid and analytical since the linking is an incremental and light-weight process.

 High Performance: With the use of Just-In-Time compilers, Java enables high performance.

2
 Distributed: Java is designed for the distributed environment of the internet.

 Dynamic: Java is considered to be more dynamic than C or C++ since it is designed to adapt to an evolving
environment. Java programs can carry extensiveamount of run-time information that can be used to verify and
resolve accesses to objects on run-time.

History of Java
James Gosling initiated Java language project in June 1991 for use in one of his many set-top box projects. The language,
initially called ‘Oak’ after an oak tree that stood outside Gosling's office, also went by the name ‘Green’ and ended up later
being renamed as Java,from a list of random words.
Sun released the first public implementation as Java 1.0 in 1995. It promised Write Once,Run Anywhere (WORA), providing
no-cost run-times on popular platforms.
On 13 November, 2006, Sun released much of Java as free and open source software under the terms of the GNU General
Public License (GPL).
On 8 May, 2007, Sun finished the process, making all of Java's core code free and open- source, aside from a small portion of
code to which Sun did not hold the copyright.

ToolsYouWill Need
For performing the examples discussed in this tutorial, you will need a Pentium 200-MHz computer with a minimum of 64
MB of RAM (128 MB of RAM recommended).
You will also need the following softwares:
 Linux 7.1 or Windows xp/7/8 operating system
 Java JDK 8
 Microsoft Notepad or any other text editor

This tutorial will provide the necessary skills to create GUI, networking, and webapplications using Java.

Try It Option
We have provided you with an option to compile and execute available code online. Just click the Try it button avaiable at
the top-right corner of the code window to compile andexecute the available code. There are certain examples which cannot
be executed online,so we have skipped those examples.

public class MyFirstJavaProgram {

public static void main(String []args) {


System.out.println("Hello World");
}
}
There may be a case that you do not see the result of the compiled/executed code. In such case, you can re-try to compile and
execute the code using execute button available

in the compilation pop-up window. Java

What is Next?
The next chapter will guide you to how you can obtain Java and its documentation. Finally,it instructs you on how to install
Java and prepare an environment to develop Java applications.

2.Java Environment-Setup
In this chapter, we will discuss on the different aspects of setting up a congenial environment for Java.

3
TryitOptionOnline
You really do not need to set up your own environment to start learning Java programminglanguage. Reason is very simple, we
already have Java Programming environment setup online, so that you can compile and execute all the available examples
online at the sametime when you are doing your theory work. This gives you confidence in what you are reading and to check
the result with different options. Feel free to modify any example and execute it online.
Try the following example using Try it option available at the top right corner of the following sample code box:

public class MyFirstJavaProgram {

public static void main(String []args) {


System.out.println("Hello World");
}
}
For most of the examples given in this tutorial, you will find the Try it option, which you can use to execute your programs
and enjoy your learning.

Local Environment Setup


If you are still willing to set up your environment for Java programming language, then this section guides you on how to
download and set up Java on your machine. Following are the steps to set up the environment.
Java SE is freely available from the link Download Java. You can download a version basedon your operating system.
Follow the instructions to download Java and run the .exe to install Java on your machine.Once you installed Java on your
machine, you will need to set environment variables to point to correct installation directories:

Setting Up the Path for Windows


Assuming you have installed Java in c:\Program Files\java\jdk directory:
Right-click on 'My Computer' and select 'Properties'.

Click the 'Environment variables' button under the 'Advanced' tab.

4
Java

Now, alter the 'Path' variable so that it also contains the path to the Java executable. Example, if the path is currently set to
'C:\WINDOWS\SYSTEM32', thenchange your path to read 'C:\WINDOWS\SYSTEM32;c:\Program Files\java\jdk\bin'.

Setting Up the Path for Linux, UNIX, Solaris, FreeBSD


Environment variable PATH should be set to point to where the Java binaries have been installed. Refer to your shell
documentation, if you have trouble doing this.
Example, if you use bash as your shell, then you would add the following line to the endof your '.bashrc: export
PATH=/path/to/java:$PATH'

Popular Java Editors


To write your Java programs, you will need a text editor. There are even more sophisticated IDEs available in the market.
But for now, you can consider one of the following:
 Notepad: On Windows machine, you can use any simple text editor like Notepad (Recommended for this tutorial),
TextPad.

 Netbeans: A Java IDE that is open-source and free, which can be downloaded from
http://www.netbeans.org/index.html.

 Eclipse: A Java IDE developed by the eclipse open-source community and can bedownloaded from
http://www.eclipse.org/.

Java
What is Next?
Next chapter will teach you how to write and run your first Java program and some of theimportant basic syntaxes in Java
needed for developing applications.

3. Java Basic Systax:

When we consider a Java program, it can be defined as a collection of objects that communicate via invoking each other's
methods. Let us now briefly look into what do class, object, methods, and instance variables mean.
 Object - Objects have states and behaviors. Example: A dog has states - color, name, breed as well as behavior such
as wagging their tail, barking, eating. An object is an instance of a class.

 Class - A class can be defined as a template/blueprint that describes the behavior/state that the object of its type
supports.

 Methods - A method is basically a behavior. A class can contain many methods. It is in methods where the logics
are written, data is manipulated and all the actions are executed.

 Instance Variables - Each object has its unique set of instance variables. An object's state is created by the values
assigned to these instance variables.

FirstJava Program
Let us look at a simple code that will print the words Hello World.

5
Java

public class MyFirstJavaProgram {

/* This is my first java program.


* This will print 'Hello World' as the output
*/

public static void main(String []args) {


System.out.println("Hello World"); // prints Hello World
}
}
Let's look at how to save the file, compile, and run the program. Please follow thesubsequent steps:
 Open notepad and add the code as above.

 Save the file as: MyFirstJavaProgram.java.

 Open a command prompt window and go to the directory where you saved theclass. Assume it's C:\.

 Type 'javac MyFirstJavaProgram.java' and press enter to compile your code. If there are no errors in your code, the
command prompt will take you to the next line (Assumption : The path variable is set).

 Now, type ' java MyFirstJavaProgram ' to run your program.

 You will be able to see ' Hello World ' printed on the window.

C:\> javac MyFirstJavaProgram.java


C:\> java MyFirstJavaProgram
Hello World

Basic Syntax
About Java programs, it is very important to keep in mind the following points.
 Case Sensitivity - Java is case sensitive, which meansidentifier
Helloand hello would have different meaning in Java.

 Class Names - For all class names the first letter should be in Upper Case.

 If several words are used to form a name of the class, each inner word's first lettershould be in Upper Case.

 Example: class MyFirstJavaClass

 Method Names - All method names should start with a Lower Case letter.

 If several words are used to form the name of the method, then each inner word'sfirst letter should be in Upper Case.

 Example: public void myMethodName()

 Program File Name - Name of the program file should exactly match the classname.

 When saving the file, you should save it using the class name (Remember Java iscase sensitive) and append '.java' to
the end of the name (if the file name and theclass name do not match, your program will not compile).
6
Java

 Example: Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved as
'MyFirstJavaProgram.java'

 public static void main(String args[]) - Java program processing starts fromthe main() method which is a
mandatory part of every Java program.

Java Identifiers
All Java components require names. Names used for classes, variables, and methods arecalled identifiers.
In Java, there are several points to remember about identifiers. They are as follows:
 All identifiers should begin with a letter (A to Z or a to z), currency character ($)or an underscore (_).

 After the first character, identifiers can have any combination of characters.

 A key word cannot be used as an identifier.

 Most importantly, identifiers are case sensitive.

 Examples of legal identifiers: age, $salary, _value, 1_value.

 Examples of illegal identifiers: 123abc, -salary.

Java Modifiers
Like other languages, it is possible to modify classes, methods, etc., by using modifiers. There are two categories of
modifiers:

 Access Modifiers: default, public , protected, private

 Non-access Modifiers: final, abstract, strictfp

We will be looking into more details about modifiers in the next section.

Java Variables
Following are the types of variables in Java:

 Local Variables
 Class Variables (Static Variables)
 Instance Variables (Non-static Variables)

Java Arrays
Arrays are objects that store multiple variables of the same type. However, an array itselfis an object on the heap. We will
look into how to declare, construct, and initialize in the upcoming chapters.

Java Enums
Enums were introduced in Java 5.0. Enums restrict a variable to have one of only a few predefined values. The values in this
enumerated list are called enums.
With the use of enums it is possible to reduce the number of bugs in your code.
For example, if we consider an application for a fresh juice shop, it would be possible to restrict the glass size to small,
medium, and large. This would make sure that it would notallow anyone to order any size other than small, medium, or large.

7
Java
Example
class FreshJuice {

enum FreshJuiceSize{ SMALL, MEDIUM, LARGE }


FreshJuiceSize size;
}

public class FreshJuiceTest {

public static void main(String args[]){


FreshJuice juice = new FreshJuice();
juice.size = FreshJuice.FreshJuiceSize.MEDIUM ;
System.out.println("Size: " + juice.size);
}
}

The above example will produce the following result:

Size: MEDIUM
Note: Enums can be declared as their own or inside a class. Methods, variables,constructors can be defined inside enums as
well.

Java Keywords
The following list shows the reserved words in Java. These reserved words may not beused as constant or variable or any
other identifier names.

abstract assert boolean break

byte case catch char

class const continue default

do double else enum

extends final finally float

for goto if implements

import instanceof int interface

long native new package

private protected public return

8
Java
short static strictfp super

switch synchronized this throw

throws transient try void

volatile while

Comments in Java
Java supports single-line and multi-line comments very similar to C and C++. Allcharacters available inside any comment
are ignored by Java compiler.

public class MyFirstJavaProgram{

/* This is my first java program.


* This will print 'Hello World' as the output
* This is an example of multi-line comments.
*/

public static void main(String []args){


// This is an example of single line comment
/* This is also an example of single line comment. */
System.out.println("Hello World");
}
}

Using BlankLines
A line containing only white space, possibly with a comment, is known as a blank line, andJava totally ignores it.

Inheritance
In Java, classes can be derived from classes. Basically, if you need to create a new class and here is already a class that has
some of the code you require, then it is possible to derive your new class from the already existing code.
This concept allows you to reuse the fields and methods of the existing class without havingto rewrite the code in a new class.

9
Java
In this scenario, the existing class is called the superclass and the derived class is called the subclass.

Interfaces
In Java language, an interface can be defined as a contract between objects on how to communicate with each other.
Interfaces play a vital role when it comes to the concept ofinheritance.
An interface defines the methods, a deriving class (subclass) should use. But theimplementation of the methods is totally up
to the subclass.

What is Next?
The next section explains about Objects and classes in Java programming. At the end of the session, you will be able to get a
clear picture as to what are objects and what are classes in Java.

10
4. Java Object and Classes
Java is an Object-Oriented Language. As a language that has the Object-Oriented feature,Java supports the following
fundamental concepts:
 Polymorphism
 Inheritance
 Encapsulation
 Abstraction
 Classes
 Objects
 Instance
 Method
 Message Parsing

In this chapter, we will look into the concepts - Classes and Objects.
 Object - Objects have states and behaviors. Example: A dog has states - color, name, breed as well as behaviors –
wagging the tail, barking, eating. An object isan instance of a class.

 Class - A class can be defined as a template/blueprint that describes the behavior/state that the object of its type
support.

ObjectsinJava
Let us now look deep into what are objects. If we consider the real-world, we can find many objects around us, cars, dogs,
humans, etc. All these objects have a state and a behavior.
If we consider a dog, then its state is - name, breed, color, and the behavior is - barking,wagging the tail, running.
If you compare the software object with a real-world object, they have very similar characteristics.
Software objects also have a state and a behavior. A software object's state is stored in fields and behavior is shown via
methods.
So in software development, methods operate on the internal state of an object and the object-to-object communication is
done via methods.

11
Classes in Java
A class is a blueprint from which individual objects are created. Following is a sample of a class.

public class Dog{


String breed;
int ageC
String color;

void barking(){
}

void hungry(){
}

void sleeping(){
}
}
A class can contain any of the following variable types.
 Local variables: Variables defined inside methods, constructors or blocks are called local variables. The variable
will be declared and initialized within the method and the variable will be destroyed when the method has
completed.

 Instance variables: Instance variables are variables within a class but outside any method. These variables are
initialized when the class is instantiated. Instance variables can be accessed from inside any method, constructor or
blocks of that particular class.

 Class variables: Class variables are variables declared within a class, outside anymethod, with the static keyword.

A class can have any number of methods to access the value of various kinds of methods.In the above example, barking(),
hungry() and sleeping() are methods.
Following are some of the important topics that need to be discussed when looking into classes of the Java Language.

Constructors
When discussing about classes, one of the most important sub topic would be constructors. Every class has a constructor. If we do
not explicitly write a constructor for a class, the Java compiler builds a default constructor for that class.
Each time a new object is created, at least one constructor will be invoked. The main ruleof constructors is that they should
have the same name as the class. A class can have more than one constructor.
Following is an example of a constructor:

public class Puppy{


public Puppy(){
}

public Puppy(String name){


// This constructor has one parameter, name.
}
}
Java also supports Singleton Classes where you would be able to create only one instanceof a class.
Note: We have two different types of constructors. We are going to discuss constructors in detail in the subsequent chapters.

How to Use SingletonClass?


The Singleton's purpose is to control object creation, limiting the number of objects to onlyone. Since there is only one Singleton
instance, any instance fields of a Singleton will occuronly once per class, just like static fields. Singletons often control access
to resources, such as database connections or sockets.
For example, if you have a license for only one connection for your database or your JDBCdriver has trouble with
multithreading, the Singleton makes sure that only one connectionis made or that only one thread can access the connection at
a time.

Implementing Singletons

Example 1
The easiest implementation consists of a private constructor and a field to hold its result,and a static accessor method with a
name like getInstance().
The private field can be assigned from within a static initializer block or, more simply, using an initializer. The getInstance( )
method (which must be public) then simply returnsthis instance −
// File Name: Singleton.java
public class Singleton {

private static Singleton singleton = new Singleton( );

/* A private Constructor prevents any other


* class from instantiating.
*/
private Singleton(){ }

/* Static 'instance' method */


public static Singleton getInstance( ) {
return singleton;
}
/* Other methods protected by singleton-ness */
protected static void demoMethod( ) {
System.out.println("demoMethod for singleton");
}
}
Here is the main program file, where we will create a singleton object:

// File Name: SingletonDemo.java


public class SingletonDemo {
public static void main(String[] args) {
Singleton tmp = Singleton.getInstance( );
tmp.demoMethod( );
}
}

This will produce the following result −

demoMethod for singleton

Example 2
Following implementation shows a classic Singleton design pattern:
public class ClassicSingleton {

private static ClassicSingleton instance = null;


private ClassicSingleton() {
// Exists only to defeat instantiation.
}
public static ClassicSingleton getInstance() {
if(instance == null) {
instance = new ClassicSingleton();
}
return instance;
} }

The ClassicSingleton class maintains a static reference to the lone singleton instance andreturns that reference from the static
getInstance() method.
Here, ClassicSingleton class employs a technique known as lazy instantiation to create thesingleton; as a result, the singleton
instance is not created until the getInstance() methodis called for the first time. This technique ensures that singleton instances
are created onlywhen needed.

Creating an Object
As mentioned previously, a class provides the blueprints for objects. So basically, an objectis created from a class. In Java, the
new keyword is used to create new objects.
There are three steps when creating an object from a class:

 Declaration: A variable declaration with a variable name with an object type.

 Instantiation: The 'new' keyword is used to create the object.

 Initialization: The 'new' keyword is followed by a call to a constructor. This callinitializes the new object.

Following is an example of creating an object:

public class Puppy{

public Puppy(String name){


// This constructor has one parameter, name.
System.out.println("Passed Name is :" + name );
}

public static void main(String []args){


// Following statement would create an object myPuppy
Puppy myPuppy = new Puppy( "tommy" );
}
}
If we compile and run the above program, then it will produce the following result:

Passed Name is :tommy

Accessing Instance Variables and Methods


Instance variables and methods are accessed via created objects. To access an instancevariable, following is the fully
qualified path:

/* First create an object */


ObjectReference = new Constructor();

/* Now call a variable as follows */


ObjectReference.variableName;

/* Now you can call a class method as follows */


ObjectReference.MethodName();

Example
This example explains how to access instance variables and methods of a class.

public class
Puppy{

int puppyAge;

public Puppy(String name){


// This constructor has one parameter, name.
System.out.println("Name chosen is :" + name );
}

public void setAge( int


age ){puppyAge = age;
}

public int getAge( ){


System.out.println("Puppy's age is :" + puppyAge );
return puppyAge;
}

public static void main(String []args){


/* Object creation */
Puppy myPuppy = new Puppy( "tommy" );

/* Call class method to set puppy's age


*/myPuppy.setAge( 2 );

/* Call another class method to get puppy's age */


myPuppy.getAge( );

/* You can access instance variable as follows as well */


System.out.println("Variable Value :" + myPuppy.puppyAge );
}
}
If we compile and run the above program, then it will produce the following result:

Name chosen is :tommy


Puppy's age is :2
Variable Value :2

Source File DeclarationRules


As the last part of this section, let's now look into the source file declaration rules. Theserules are essential when declaring
classes, import statements and package statements ina source file.
 There can be only one public class per source file.

 A source file can have multiple non-public classes.

 The public class name should be the name of the source file as well which should be appended by .java at the end.
For example: the class name is public class Employee{} then the source file should be as Employee.java.

 If the class is defined inside a package, then the package statement should be thefirst statement in the source file.

 If import statements are present, then they must be written between the packagestatement and the class declaration.
If there are no package statements, then theimport statement should be the first line in the source file.

 Import and package statements will imply to all the classes present in the source file. It is not possible to declare
different import and/or package statements to different classes in the source file.
Classes have several access levels and there are different types of classes; abstract classes, final classes, etc. We will be
explaining about all these in the access modifiers chapter.
Apart from the above mentioned types of classes, Java also has some special classes calledInner classes and Anonymous
classes.
Model View Controller (MVC) Pattern
MVC Architecture in Java
The Model-View-Controller (MVC) is a well-known design pattern in the web development field. It is
way to organize our code. It specifies that a program or application shall consist of data model,
presentation information and control information. The MVC pattern needs all these components to be
separated as different objects.

In this section, we will discuss the MVC Architecture in Java, alongwith its advantages and
disadvantages and examples to understand the implementation of MVC in Java.

What is MVC architecture in Java?


The model designs based on the MVC architecture follow MVC design pattern. The application logic is
separated from the user interface while designing the software using model designs.

The MVC pattern architecture consists of three layers:

 Model - Model represents an object or JAVA POJO carrying data. It can also have logic to
update controller if its data changes.
 View - View represents the visualization of the data that model contains.
 Controller - Controller acts on both model and view. It controls the data flow into model object
and updates the view whenever data changes. It keeps view and model separate.
Implementation
 We are going to create a Student object acting as a model.StudentView will be a view class which
can print student details on console and StudentController is the controller class responsible to
store data in Student object and update view StudentView accordingly.
 MVCPatternDemo, our demo class, will use StudentController to demonstrate use of MVC
pattern.

Step 1
Create Model.

Student.java

public class Student {


private String rollNo;
private String name;

public String getRollNo() {


return rollNo;
}

public void setRollNo(String rollNo) {


this.rollNo = rollNo;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}
}
Step 2
Create View.

StudentView.java

public class StudentView {


public void printStudentDetails(String studentName, String studentRollNo){
System.out.println("Student: ");
System.out.println("Name: " + studentName);
System.out.println("Roll No: " + studentRollNo);
}
}
Step 3
Create Controller.

StudentController.java

public class StudentController {


private Student model;
private StudentView view;

public StudentController(Student model, StudentView view){


this.model = model;
this.view = view;
}

public void setStudentName(String name){


model.setName(name);
}

public String getStudentName(){


return model.getName();
}

public void setStudentRollNo(String rollNo){


model.setRollNo(rollNo);
}

public String getStudentRollNo(){


return model.getRollNo();
}

public void updateView(){


view.printStudentDetails(model.getName(), model.getRollNo());
}
}
Step 4
Use the StudentController methods to demonstrate MVC design pattern usage.

MVCPatternDemo.java
public class MVCPatternDemo {
public static void main(String[] args) {

//fetch student record based on his roll no from the database


Student model = retriveStudentFromDatabase();

//Create a view : to write student details on console


StudentView view = new StudentView();

StudentController controller = new StudentController(model, view);

controller.updateView();

//update model data


controller.setStudentName("John");

controller.updateView();
}

private static Student retriveStudentFromDatabase(){


Student student = new Student();
student.setName("Robert");
student.setRollNo("10");
return student;
}
}
Step 5
Verify the output.

Student:
Name: Robert
Roll No: 10
Student:
Name: John
Roll No: 10
MVC Architecture using Spring
Spring MVC Tutorial
A Spring MVC is a Java framework which is used to build web applications. It follows the Model-
View-Controller design pattern. It implements all the basic features of a core spring framework like
Inversion of Control, Dependency Injection.

A Spring MVC provides an elegant solution to use MVC in spring framework by the help
of DispatcherServlet. Here, DispatcherServlet is a class that receives the incoming request and maps it
to the right resource such as controllers, models, and views.

The DispatcherServlet
The Spring Web model-view-controller (MVC) framework is designed around a DispatcherServlet that
handles all the HTTP requests and responses. The request processing workflow of the Spring Web
MVC DispatcherServlet is illustrated in the following diagram −

Following is the sequence of events corresponding to an incoming HTTP request to DispatcherServlet −

 After receiving an HTTP request, DispatcherServlet consults the HandlerMapping to call the
appropriate Controller.
 The Controller takes the request and calls the appropriate service methods based on used GET or
POST method. The service method will set model data based on defined business logic and
returns view name to the DispatcherServlet.
 The DispatcherServlet will take help from ViewResolver to pickup the defined view for the
request.
 Once view is finalized, The DispatcherServlet passes the model data to the view which is finally
rendered on the browser.
All the above-mentioned components, i.e. HandlerMapping, Controller, and ViewResolver are parts
of WebApplicationContext which is an extension of the plainApplicationContext with some extra
features necessary for web applications.

Required Configuration
You need to map requests that you want the DispatcherServlet to handle, by using a URL mapping in
the web.xml file. The following is an example to show declaration and mapping
for HelloWeb DispatcherServlet example −

<web-app id = "WebApp_ID" version = "2.4"


xmlns = "http://java.sun.com/xml/ns/j2ee"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Spring MVC Application</display-name>

<servlet>
<servlet-name>HelloWeb</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>HelloWeb</servlet-name>
<url-pattern>*.jsp</url-pattern>
</servlet-mapping>

</web-app>
The web.xml file will be kept in the WebContent/WEB-INF directory of your web application. Upon
initialization of HelloWeb DispatcherServlet, the framework will try to load the application context
from a file named [servlet-name]-servlet.xml located in the application's WebContent/WEB-INF
directory. In this case, our file will be HelloWebservlet.xml.

Next, <servlet-mapping> tag indicates what URLs will be handled by which DispatcherServlet. Here all
the HTTP requests ending with .jsp will be handled by the HelloWeb DispatcherServlet.

If you do not want to go with default filename as [servlet-name]-servlet.xml and default location
as WebContent/WEB-INF, you can customize this file name and location by adding the servlet
listener ContextLoaderListener in your web.xml file as follows −

<web-app...>

<!-------- DispatcherServlet definition goes here----->


....
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/HelloWeb-servlet.xml</param-value>
</context-param>

<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>

</web-app>
Now, let us check the required configuration for HelloWeb-servlet.xml file, placed in your web
application's WebContent/WEB-INF directory −

<beans xmlns = "http://www.springframework.org/schema/beans"


xmlns:context = "http://www.springframework.org/schema/context"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<context:component-scan base-package = "com.tutorialspoint" />

<bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">


<property name = "prefix" value = "/WEB-INF/jsp/" />
<property name = "suffix" value = ".jsp" />
</bean>

</beans>
Following are the important points about HelloWeb-servlet.xml file −

 The [servlet-name]-servlet.xml file will be used to create the beans defined, overriding the
definitions of any beans defined with the same name in the global scope.
 The <context:component-scan...> tag will be use to activate Spring MVC annotation scanning
capability which allows to make use of annotations like @Controller and @RequestMapping etc.
 The InternalResourceViewResolver will have rules defined to resolve the view names. As per the
above defined rule, a logical view named hello is delegated to a view implementation located
at /WEB-INF/jsp/hello.jsp .
The following section will show you how to create your actual components, i.e., Controller, Model, and
View.

Defining a Controller
 The DispatcherServlet delegates the request to the controllers to execute the functionality
specific to it. The @Controller annotation indicates that a particular class serves the role of a
controller. The @RequestMapping annotation is used to map a URL to either an entire class or
a particular handler method.

@Controller
@RequestMapping("/hello")
public class HelloController {
@RequestMapping(method = RequestMethod.GET)
public String printHello(ModelMap model) {
model.addAttribute("message", "Hello Spring MVC Framework!");
return "hello";
}
}
The @Controller annotation defines the class as a Spring MVC controller. Here, the first usage
of @RequestMapping indicates that all handling methods on this controller are relative to
the /hello path. Next annotation @RequestMapping(method = RequestMethod.GET) is used to
declare the printHello() method as the controller's default service method to handle HTTP GET request.
You can define another method to handle any POST request at the same URL.

You can write the above controller in another form where you can add additional attributes
in @RequestMapping as follows −

@Controller
public class HelloController {
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String printHello(ModelMap model) {
model.addAttribute("message", "Hello Spring MVC Framework!");
return "hello";
}
}
The value attribute indicates the URL to which the handler method is mapped and the method attribute
defines the service method to handle HTTP GET request. The following important points are to be noted
about the controller defined above −


You will define required business logic inside a service method. You can call another method
inside this method as per requirement.
 Based on the business logic defined, you will create a model within this method. You can use
setter different model attributes and these attributes will be accessed by the view to present the
final result. This example creates a model with its attribute "message".
 A defined service method can return a String, which contains the name of the view to be used to
render the model. This example returns "hello" as logical view name.
Creating JSP Views
Spring MVC supports many types of views for different presentation technologies. These include - JSPs,
HTML, PDF, Excel worksheets, XML, Velocity templates, XSLT, JSON, Atom and RSS feeds,
JasperReports, etc. But most commonly we use JSP templates written with JSTL.

Let us write a simple hello view in /WEB-INF/hello/hello.jsp −

<html>
<head>
<title>Hello Spring MVC</title>
</head>

<body>
<h2>${message}</h2>
</body>
</html>
Here ${message} is the attribute which we have set up inside the Controller. You can have multiple
attributes to be displayed inside your view.

Spring Web MVC Framework Examples


Based on the above concepts, let us check few important examples which will help you in building your
Spring Web Applications −

Sr.No. Example & Description

Spring MVC Hello World Example


1 This example will explain how to write a simple Spring Web Hello World
application.

Spring MVC Form Handling Example


2 This example will explain how to write a Spring Web application using HTML
forms to submit the data to the controller and display a processed result.

Spring Page Redirection Example


3
Learn how to use page redirection functionality in Spring MVC Framework.

Spring Static Pages Example


4 Learn how to access static pages along with dynamic pages in Spring MVC
Framework.

Spring Exception Handling Example


5
Learn how to handle exceptions in Spring MVC Framework.

RESTful API using Spring Framework

Web-based application development is a common part of Java development. It is part and parcel of the
enterprise domain wherein they share many common attributes of building a production-ready
application. Spring uniquely addresses the concern for building a Web application through its MVC
framework. It is called MVC because it is based upon the MVC (Model-View-Controller) pattern. Refer
to Wikipedia: Model-view-controller for quick information about this. Web applications, in most cases,
have a REST counterpart for resource sharing. This article builds up on both the idea and ends with a
quick example to describe them in a terse manner.

Spring MVC
A Web application is inherently multi-layered because the intricacies between the user request and
server response go through several in-between stages of information processing. Each stage is handled
by a layer. For example, the Web interaction begins with user interaction with the browser, such as by
triggering a request and getting a response from the server. The request response paradigm is nothing
more than an exchange of certain arranged data, which can be anywhere from trivial to heavily loaded
information gathered from, for example, a form submitted by the user. The URL encapsulates the
request from the user and flutters into the network oblivion. Voilà! It is returned back with the digital
PIZZA you have requested onto the platter called a browser. The request actually goes through a bunch
of agents under the purview of the Spring MVC framework. Each of these agents performs specific
functions, technically called request processing, before actually responding back to the requester. Here
is an illustration to give you an idea.

Figure 1: The Spring framework

1. The journey begins with the HTTP request (sometimes with data payload; for example, due to form
submission) in a URL. It first stations at DispatcherServlet. The DispatcherServlet is a class defined
in the org.springframework.web.servlet package. It is the central dispatcher, a Java Servlet
Component for the Spring MVC framework. This front controller receives all incoming HTTP client
requests and delegates responsibilities to other components for further processing of the request
payload.
2. The handler mapping decides where the request’s next stop would be. It acts as a consultant to the
central dispatcher (DispatcherServlet) for routing the request to the appropriate controller. The
handler mapping parses the request URL to make decisions and the dispatcher then delegates the
request to the controller.
3. The controller‘s responsibility is to process the information payload received from the request.
Typically, a controller is associated with one or more business service classes which, in turn, may
have associated database services repository classes. The repository classes fetch database
information according to the business service logic. It is the business service classes that contain the
crux of processing. The controller class simply carries the information received from one or more
service classes to the user. However, the response of the controller classes is still raw data referred to
as the model and may not be user friendly (with indentation, bullets, tables, images, look-and-feel,
and so forth).
4. Therefore, the controller packages the model data along with model and view name back again to
the central dispatcher, DispatcherServlet.
5. The view layer can be designed using any third-party framework such as Node.js, Angular, JSP, and
so on. The controller is decoupled from the view by passing the view name to
the DispatcherServlet and is least interested in it. The DispatcherServlet simply carries the logical
name and consults with the view resolver to map the logical view name with the actual
implementation.
6. Once the mapping between logical view name and the actual view implementation is made,
the DispatcherServlet delegates the responsibility of rendering model data to the view
implementation.
7. The view implementation finally carries the response back to the client browser.
REST
REST is the acronym of Representational State Transfer. It is a term coined in Roy Thomas Fielding’s
doctoral thesis where REST is a part that encompasses the architecture of transferring the state of
resources. The REST architecture is made popular as an alternative to a SOAP implementation of Web
services. Although REST has a much wider connotation than just Web services, here we’ll limit our
discussion to dealing with REST resources only. The idea Web services are basically resource sharing in
the Web architecture that forms the cornerstone of distributed machine-to-machine communication. The
Spring MVC framework resides pretty well with REST and provides the necessary API support to
implement it seamlessly, with little effort.

The URL and HTTP Methods


The REST resources are located on a remote host using URL. The idea is based on the foundation of the
protocol called HTTP. For example, the URL http://www.payroll.com/employees may mean a list of
employees to search and http://www.payroll.com/employees/101 may mean the detail of an employee
with, say, ID 101. Hence, the URL/URI actually represents the actual location of a resource on the Web.
The resource may be anything a Web page, an image, audio, video content, or the like. The HTTP
protocol specifies several methods. If they are combined with the URL that points to the resource, we
can get the following CRUD results as outlined below.
URL Method Outcome
http://www.payroll.com/employees POST Creates a list of employees
http://www.payroll.com/employees PUT or PATCH Updates a list of employees
http://www.payroll.com/employees DELETE Deletes a list of employees
http://www.payroll.com/employees GET Gets a list of employees
http://www.payroll.com/employees/101 POST Creates a employee with ID 101
http://www.payroll.com/employees/101 PUT or PATCH Updates employee with ID 101
http://www.payroll.com/employees/101 DELETE Deletes employee with ID 101
http://www.payroll.com/employees/101 GET Gets employee details with ID 101

Though the URL is associated with HTTP methods in REST, there are no strict rules to adhere to the
outcome described above. The point is that RESTful URL structure should be able to locate a resource
on the server. For instance, the PUT instruction can be used to create a new resource and POST can be
used to update a resource.

REST in Spring
The REST API support was introduced in Spring from version 3.0 onwards; since then, it has steadily
evolved to the present day. We can create REST resources in the following ways:

 Using controllers which are used to handle HTTP requests such as GET, POST, PUT, and so forth.
The PATCH command is supported by Spring 3.2 and higher versions.
 Using the @PathVariable annotation. This annotation is used to handle parameterized URLs. This is
usually associated with the @RequestMapping handler method in a Servlet environment.
 There are multiple ways to represent a REST resource using Spring views and view resolvers with
rendering model data as XML, JSON, Atom, and RSS.
 The type of model data view suits the client can be resolved via ContentNegotiatingViewResolver.
The ContentNegotiatingViewResolver, however, does not resolve views itself but delegates to
other ViewResolvers. By default, these other view resolvers are picked up automatically from the
application context, though they can also be set explicitly by using the viewResolver property.
 Consuming REST resources using RestTemplate.

A Quick Example: Creating a Simple REST Endpoint


When working with REST services with Spring, we either publish application data as a REST service or
access data in the application from third-party REST services. Here in this sample application, we
combine Spring MVC to work with a REST endpoint in a controller named EmployeeController.
Firstly, we create a model class named Employee. This may be designated with JPA annotation to persist
in the backend database. But, to keep it simple, we’ll not use JPA; instead, we’ll supply dummy data
through the EmployeeService class. In a real situation, data is fetched from the backend database server
and the data access methods are defined in a repository class. To give a hint, in our case, if we had used
JPA with a back-end database, it may have been an interface that extends CrudRepository, something
like this.

public interface EmployeeRepository extends

CrudRepository<Employee, String>{

// ...

Employee.java
package com.mano.spring_mvc_rest_example.spring_mvc_rest.employee;
public class Employee {
private String id;
private String name;
private String address;
public Employee() {
}
public Employee(String id, String name, String address) {
this.id = id;
this.name = name;
this.address = address;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}

EmployeeService.java
package com.mano.spring_mvc_rest_example.spring_
mvc_rest.employee;
import org.springframework.stereotype.Service;
import java.util.Arrays;
import java.util.List;
@Service
public class EmployeeService {
List<Employee> employeeList= Arrays.asList(
new Employee("spiderman","Peter Parker",
"New York"),
new Employee("batman","Bruce Wayne",
"Gotham City"),
new Employee("superman","Clark Kent",
"Metropolis"),
new Employee("blackpanther","T'Challa",
"Wakanda"),
new Employee("ironman","Tony Stark",
"New York")
);
public List<Employee> getEmployees(){
return employeeList;
}
public Employee getEmployee(String id){
return employeeList.stream().filter(e->e.getId()
.equals(id)).findFirst().get();
}
public void addEmployee(Employee employee){
}
public void updateEmployee(Employee employee, String id){
for(int i=0;i<employeeList.size();i++){
Employee e=employeeList.get(i);
if(e.getId().equals(id)) {
employeeList.set(i, employee);
break;
}
}
}
public void deleteEmployee(String id){
employeeList.removeIf(e->e.getId().equals(id));
}
}

EmployeeController.java
package com.mano.spring_mvc_rest_example.spring_mvc_rest.employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
public class EmployeeController {
@Autowired
private EmployeeService employeeService;
@RequestMapping("/employees")
public List<Employee> getEmployees(){
return employeeService.getEmployees();
}
@RequestMapping("/employees/{empid}")
public Employee getEmployee(@PathVariable("empid")
String id){
return employeeService.getEmployee(id);
}
@RequestMapping(method= RequestMethod.POST,
value="/employees")
public void addEmployee(@RequestBody Employee employee){
employeeService.addEmployee(employee);
}
@RequestMapping(method = RequestMethod.PUT,
value="/employees/{id}")
public void updateEmployee(@RequestBody Employee employee,
@PathVariable String id){
employeeService.updateEmployee(employee, id);
}
@RequestMapping(method = RequestMethod.DELETE,
value="/employees/{id}")
public void deleteEmployee(@PathVariable String id){
employeeService>.deleteEmployee(id);
}
}
 Observe that the Web controller class named EmployeeController is designated as
a @RestController annotation. This is a convenience annotation that actually combines
the @Controller and @ResponseBody annotations. The @Controller annotation designates a
POJO as a Web controller and is a specialization of @Component. When we designate a POJO
class with @Controller or @Component, or even a @RestController, Spring auto detects them
by considering them as a candidate while class path scanning. The @ResponseBody annotation
indicates that the method response value should be bound to the Web response body.
The valid URL requests for publishing REST resources for the above code are as follows:

 Get all employees: http://localhost:8080/employees


 Get one employee: http://localhost:8080/employees/batman
Conclusion
For REST CRUD operations such as adding, updating, and deleting Employee, we need a HTTP client
application that enables us to test Web services, such as postman; otherwise, we need to implement the
view layer of the application with the help of JavaScript frameworks such as jQuery, AngularJS, and the
like. To keep the write-up well within limits, we have not implemented them here. If possible, we’ll take
them up in a separate write-up. By the way, we have only scratched the surface of Spring MVC and
Spring REST support. Take this as a warm-up before the deep plunge you may want to take into the
stream of Spring. As you swim across, you’ll find many interesting sight scenes.

Building an application using Maven


What is Maven Lifecycle
This is a query frequently posed in the field of software development. Maven is fundamentally
structured around the concept of a build lifecycle. Here is the list that will explain everything about the
maven life cycle:

 Maven is built around the concept of a build lifecycle, which defines the order of execution for goals.
 The default Maven lifecycle consists of 8 major phases: Validate, Compile, Test, Package, Integration
Test, Verify, Install, and Deploy.
 Each phase represents a specific step in the build process and has its own set of goals to be executed.
 For example, the Compile phase compiles the source code, the Test phase runs unit tests, and the Package
phase creates a distributable artifact.
 Maven follows a sequential order, where executing a specific phase also triggers the preceding phases.
 Goals in Maven represent granular tasks and are packaged in plugins.
 Plugins contain one or more goals and contribute to the creation and management of the project.
 The Maven build lifecycle includes three built-in lifecycles: default, clean, and site.
 The default lifecycle handles the regular build process, the clean life cycle removes generated artifacts,
and the site life cycle generates project documentation and reports.
 Overall, the Maven lifecycle provides a structured and standardized approach to building and
managing projects, ensuring consistent and reliable results.

Phases of Maven Lifecycle


Maven Clean Lifecycle:
1. The Maven clean lifecycle consists of the following phases:
 pre-clean
 clean
 Post-clean
2. By using the Clean phase (mvn clean), you ensure a clean and consistent build environment. It
removes previously generated artifacts, reducing the risk of conflicts or outdated files.
3. Ensures that subsequent builds start from a clean state, minimizing potential build errors. Provides a
fresh workspace for developers, leading to improved productivity and reliability.

Maven Build Lifecycle:


1. The Maven build lifecycle consists of the following phases:
 validate
 compile
 test
 package
 verify
 install
 deploy
2. The Build phase (mvn compile, mvn test, mvn package, etc.) automates the compilation, testing, and
packaging processes.
3. It ensures consistent and reliable builds across different test environments.
4. Maven’s dependency management handles the resolution and integration of external libraries,
simplifying the development process.
5. Build reports and test results provide valuable insights into the project’s health and code quality.

Maven Site Lifecycle:


1. The Maven site lifecycle consists of the following phases:
 pre-site
 site
 post-site
 site-deploy
2. The site phase (mvn site) generates comprehensive project documentation, reports, and metrics. It
facilitates better understanding and collaboration among team members.
3. API documentation and code metrics help maintain code quality and adhere to best practices. Detailed
reports, such as test coverage, facilitate effective testing and quality assurance.
Read More: Maven Dependency Management with Selenium

Understanding Maven Goals and Plugins


In Maven, goals and plugins play a crucial role in executing specific tasks and extending the
functionality of the build process.
Maven Goals:

 Goals are specific tasks that Maven can perform during the build lifecycle.
 Each phase of the lifecycle is associated with one or more goals.
 Maven provides default goals for each phase, but you can also define custom goals.
 Goals can be executed from the command line using the mvn command followed by the goal name.
 Examples of common Maven goals include compile, test, package, and install.

Maven Plugins:

 Plugins are the building blocks of Maven’s functionality.


 They provide implementations for various goals and can be used to extend the build process.
 Maven has a vast ecosystem of plugins that cover a wide range of tasks and integrations.
 Plugins can be configured in the project’s POM file, specifying the desired version and any custom
configurations.
 Maven resolves and downloads plugins from remote repositories when needed.
 Examples of popular Maven plugins include the Maven Compiler Plugin, Surefire Plugin for testing, and the
Maven Assembly Plugin for creating custom distributions.
Read More: What is Maven in Java? (Framework and Uses)
Benefits of Goals and Plugins:

 Goals allow you to perform specific tasks within the build lifecycle, such as compiling code, running
tests, packaging the project, or generating reports.
 Plugins provide additional functionality by implementing these goals and extending Maven’s capabilities.
 They help automate complex tasks, manage dependencies, generate documentation, and integrate with
external tools.
 Goals and plugins ensure consistency across projects and facilitate collaboration by providing a
standardized approach to building and managing projects.
 In summary, Maven goals represent specific tasks within the build lifecycle, and plugins provide
the implementations for those tasks.
 Together, they allow you to automate various aspects of the build process, extend functionality,
and achieve efficient and reliable project builds.

Setting up a Maven project


Step 1: Install Java JDK
Install Java (JDK 1.7 or higher) on your machine. Java serves as the backbone for Maven, providing the
necessary environment to bring your projects to life.
Step 2: Download Maven
Head over to the official Apache Maven website. Download the Maven binary zip file, unbox it, and let
Maven dazzle you with its capabilities.
Step 3: Configure Maven’s Path
Set up the MAVEN_HOME environment variable, pointing it to Maven’s bin folder. This helps set up
seamless communication between your system and Maven.
Step 4: Check if Maven is Installed properly
Know whether your Maven is installed correctly by checking its version. Open the command prompt,
type the below command to know the version of Maven installed.

mvn -version

Step 5: Create a new Maven Project


Create a new project in Maven with the below command.
mvn archetype:generate

Maven will create a structure for your project.


Step 6: Add Maven Dependencies
To enrich your project’s capabilities, add dependencies to your project’s pom.xml file.
Read More: Page Object Model and Page Factory in Selenium
Step 7: Create a Maven Project
Maven will compile, test, and package your project using the below command.
mvn install

 This command will build the Maven project and installs the project files ( JAR , WAR , pom.
xml , etc.) to the local repository.
 Launch your project after you complete the build.
 Maven sets the stage for a smooth, organized, and efficient project management experience.
Embrace its simplicity, and let Maven revolutionize your development journey.
 Maven exhibits different capabilities, from managing JARs and dependencies to automating
Selenium Java project lifecycles. Understand the intricacies of transitive dependencies and how
Maven simplifies their management.

Closing Notes
 Maven is widely used by prominent companies worldwide to streamline their software
development processes. Companies like Apache Software Foundation, Google, Netflix, Twitter,
LinkedIn, and PayPal rely on Maven for efficient build automation and dependency
management.
 Maven’s widespread adoption by these companies is a testament to its effectiveness in ensuring
reliable and scalable software development. By leveraging Maven’s capabilities, these
companies can manage dependencies, automate builds, and deliver high-quality software more
efficiently.

You might also like