Unit-4 FSD
Unit-4 FSD
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.
CSE,SEAT- P V RAMESH
IV SEM FSD- UNIT-4,Java Web Development 2
Java web development works on three main factors. These development factors show below.
The above three factors create, update, remove, display and operate data or information.
Front-end web development: The front-end technology interacts with the user and Java
interface. It helps to insert and submit data. Java web development uses JavaServer Pages or
JSP for the front-end form or table.
Backend web development: The backend technology maintains and updates data of the
database. Java uses Servlet, spring, and other advanced technology.
Database management handles or fetches data from the database using the Java database
driver. The Java technology uses JDBC, Hibernate to handle the database.
216 | P a g e
CSE,SEAT- P V RAMESH
IV SEM FSD- UNIT-4,Java Web Development 3
Servlet, filter, filter chain, servlet config, and other interfaces are available in the javax.
Servlet package. The capabilities of servers that host apps are increased by using Servlet.
The request-response model is used in web development applications written with Java
servlets. From initialization to garbage collection, a servlet has a life cycle.
Servlets are useful for various tasks, including collecting data via web page forms, presenting
data from a database or any other third-party source, etc.
Servlets are Java programs that run on a web application and send client requests to databases
or servers. After talking with the database, the servlets help process the client's request and
provide results.
Developers employ JavaServer Pages or JSP technology to quickly produce platform- and
server-independent online content. Normally, the developer works on separate Common
Gateway Interface files to embed dynamic elements in HTML pages. Java JSP technology
can be used, as it has access to the whole Java API family.
The JSP technology pieces code to control web information and moves dynamically. A JSP
page comprises static data written in HTML, WML, XML, and other markup languages.
Special JSP tags simplify Java code into HTML pages, making web development user-
friendly.
The JSP technology allows embedding bits of servlet code in a text-based document. JSP is a
popular Java EE technology that allows programmers to create complex dynamic web pages
quickly.
JDBC Driver is a connector between database and Java web application. Java database
217 | P a g e
CSE,SEAT- P V RAMESH
IV SEM FSD- UNIT-4,Java Web Development 4
connectivity helps to update and modify data using queries. The jdbc driver is an essential
part of Java web development. This driver helps to send data to the database and retrieve data
from the database.
Within a Java program, the JDBC driver allows to perform the following tasks:
JDBC is a set of methods and queries for accessing databases written in Java. Clients can use
web applications using JDBC drivers to update any information in the database.
JDBC drivers connect to databases in four ways: JDBC-ODBC Bridge Driver, Network
Protocol Driver, Native Driver, and Thin Driver.
For web development, the Java Persistence API employs object-relational mapping. This
mapping connects a database to an object-oriented model. Java Persistence makes it simple to
manage relational data in Java web applications. The Java Persistence API aids in database
data management. This API sends data to a database and retrieves data from it regularly.
Large amounts of code, proprietary frameworks, and other files are not required. JPA gives a
straightforward technique of database communication. A database is an object-relational
approach for interacting with Java web development. JPA is a set of lightweight classes and
methods for interacting with databases.
JavaServer Faces is called a JSF Technology. This technology provides a framework for
developing web-based interfaces. JSF provides a simple model for components in various
scripting or markup languages.
The data sources and server-side event handlers are coupled to the User Interface widgets.
JSF aids in the creation and maintenance of web applications by minimizing the time and
effort required.
The JavaServer Pages Standard Tag Library or JSTL abstracts common functionality of JSP-
based applications. We use a single standard set of tags to incorporate tags from various
vendors into web applications. This standardization enables the establishment of Java
218 | P a g e
CSE,SEAT- P V RAMESH
IV SEM FSD- UNIT-4,Java Web Development 5
applications on any JSP container. It supports JSTL and increases the tags to optimize during
implementation.
JSTL includes iterator and conditional tags for controlling flow. These tags work for
manipulating XML documents and tags for internationalization. This JSTL is also used for
SQL database access and tags for frequently used functions.
Messaging is a way for software components or apps to communicate with one another. A
messaging system is a type of peer-to-peer network. In other words, a messaging client can
communicate with and be communicated with by any other client.
Each client establishes a connection with a messaging agent, facilitating the creation,
transmission, receipt, and reading of messages.
The Java Message Service (JMS) API provides a strong tool for resolving enterprise
computing problems by integrating Java technology and enterprise messaging.
Enterprise messaging enables the secure and flexible sharing of business data. The JMS API
extends this by providing a uniform API and provider framework that facilitates the building
of portable message-based Java applications.
Conclusion
Java programming language is easy to handle and programmer's first choice for web
development. Java web development has basic rules apart from operating data. This
technology does not need an extra operation or advanced programming.
Java web development creates multiple web applications using a single type of code on
multiple pages. If we know the working procedure, then JAVA technology develops any
application.
219 | P a g e
CSE,SEAT- P V RAMESH
IV SEM FSD- UNIT-4,Java Web Development 6
What is Java?
Java is a high-level, general-purpose, object-oriented, and secure programming language
developed by James Gosling at Sun Microsystems, Inc. in 1991. It is formally known as
OAK. In 1995, Sun Microsystem changed the name to Java. In 2009, Sun Microsystem
takeover by Oracle Corporation.
Editions of Java
Each edition of Java has different capabilities. There are three editions of Java:
Java Standard Editions (JSE): It is used to create programs for a desktop computer.
Java Enterprise Edition (JEE): It is used to create large programs that run on the
server and manages heavy traffic and complex transactions.
Java Micro Edition (JME): It is used to develop applications for small devices such
as set-top boxes, phone, and appliances.
Java Platform
Java Platform is a collection of programs. It helps to develop and run a program written in the
Java programming language. Java Platform includes an execution engine, a compiler and set
of libraries. Java is a platform-independent language.
Features of Java
Simple: Java is a simple language because its syntax is simple, clean, and easy to
understand. Complex and ambiguous concepts of C++ are either eliminated or re-
implemented in Java. For example, pointer and operator overloading are not used in
Java.
Object-Oriented: In Java, everything is in the form of the object. It means it has
some data and behavior. A program must have at least one class and object.
Robust: Java makes an effort to check error at run time and compile time. It uses a
220 | P a g e
CSE,SEAT- P V RAMESH
IV SEM FSD- UNIT-4,Java Web Development 7
strong memory management system called garbage collector. Exception handling and
garbage collection features make it strong.
Secure: Java is a secure programming language because it has no explicit pointer and
programs runs in the virtual machine. Java contains a security manager that defines
the access of Java classes.
Platform-Independent: Java provides a guarantee that code writes once and run
anywhere. This byte code is platform-independent and can be run on any machine.
Class: A class is a template or blueprint or prototype that defines data members and methods
of an object. An object is the instance of the class. We can define a class by using the class
keyword.
Object: An object is a real-world entity that can be identified distinctly. For example, a desk,
a circle can be considered as objects. An object has a unique behavior, identity, and state.
Data fields with their current values represent the state of an object (also known as its
properties or attributes).
Abstraction: An abstraction is a method of hiding irrelevant information from the user. For
example, the driver only knows how to drive a car; there is no need to know how does the car
run. We can make a class abstract by using the keyword abstract. In Java, we use abstract
class and interface to achieve abstraction.
Encapsulation: An encapsulation is the process of binding data and functions into a single
unit. A class is an example of encapsulation. In Java, Java bean is a fully encapsulated class.
221 | P a g e
CSE,SEAT- P V RAMESH
IV SEM FSD- UNIT-4,Java Web Development 8
Inheritance: Inheritance is the mechanism in which one class acquire all the features of
another class. We can achieve inheritance by using the extends keyword. It facilitates the
reusability of the code.
Polymorphism: The polymorphism is the ability to appear in many forms. In other words,
single action in different ways. For example, a boy in the classroom behaves like a student, in
house behaves like a son. There are two types of polymorphism: run time polymorphism and
compile-time polymorphism.
Java Variables
A variable is a container which holds the value while the Java program is executed. A
variable is assigned with a data type.
Variable is a name of memory location. There are three types of variables in java: local,
instance and static.
There are two types of data types in Java: primitive and non-primitive.
Variable
A variable is the name of a reserved area allocated in memory. In other words, it is a name of
the memory location. It is a combination of "vary + able" which means its value can be
changed.
Types of Variables
222 | P a g e
CSE,SEAT- P V RAMESH
IV SEM FSD- UNIT-4,Java Web Development 9
local variable
instance variable
static variable
1) Local Variable
A variable declared inside the body of the method is called local variable. You can use this
variable only within that method and the other methods in the class aren't even aware that the
variable exists.
2) Instance Variable
A variable declared inside the class but outside the body of the method, is called an instance
variable. It is not declared as static.
It is called an instance variable because its value is instance-specific and is not shared among
223 | P a g e
CSE,SEAT- P V RAMESH
IV SEM FSD- UNIT-4,Java Web Development 10
instances.
3) Static variable
A variable that is declared as static is called a static variable. It cannot be local. You can
create a single copy of the static variable and share it among all the instances of the class.
Memory allocation for static variables happens only once when the class is loaded in the
memory.
1. public class A
2. {
3. static int m=100;//static variable
4. void method()
5. {
6. int n=90;//local variable
7. }
8. public static void main(String args[])
9. {
10. int data=50;//instance variable
11. }
12. }//end of class
Output:
20
Java Variable Example: Widening
Output:
10
224 | P a g e
CSE,SEAT- P V RAMESH
IV SEM FSD- UNIT-4,Java Web Development 11
10.0
Java Variable Example: Narrowing (Typecasting)
Output:
10.5
10
Java Variable Example: Overflow
1. class Simple{
2. public static void main(String[] args){
3. //Overflow
4. int a=130;
5. byte b=(byte)a;
6. System.out.println(a);
7. System.out.println(b);
8. }}
Output:
130
-126
Java Variable Example: Adding Lower Type
1. class Simple{
2. public static void main(String[] args){
3. byte a=10;
4. byte b=10;
5. //byte c=a+b;//Compile Time Error: because a+b=20 will be int
6. byte c=(byte)(a+b);
7. System.out.println(c);
8. }}
Output:
20
225 | P a g e
CSE,SEAT- P V RAMESH
IV SEM FSD- UNIT-4,Java Web Development 12
In this page, we will learn about the basics of OOPs. Object-Oriented Programming is a
paradigm that provides many concepts, such as inheritance, data binding, polymorphism,
etc.
The popular object-oriented languages are Java, C#, PHP, Python, C++, etc.
Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation
Apart from these concepts, there are some other terms which are used in Object-Oriented
design:
Coupling
Cohesion
Association
Aggregation
Composition
226 | P a g e
CSE,SEAT- P V RAMESH
IV SEM FSD- UNIT-4,Java Web Development 13
Object
Any entity that has state and behavior is known as an object. For example, a chair, pen, table,
keyboard, bike, etc. It can be physical or logical.
An Object can be defined as an instance of a class. An object contains an address and takes
227 | P a g e
CSE,SEAT- P V RAMESH
IV SEM FSD- UNIT-4,Java Web Development 14
up some space in memory. Objects can communicate without knowing the details of each
other's data or code. The only necessary thing is the type of message accepted and the type of
response returned by the objects.
Example: A dog is an object because it has states like color, name, breed, etc. as well as
behaviors like wagging the tail, barking, eating, etc.
Class
Collection of objects is called class. It is a logical entity.
A class can also be defined as a blueprint from which you can create an individual object.
Class doesn't consume any space.
Inheritance
When one object acquires all the properties and behaviors of a parent object, it is known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
Polymorphism
Another example can be to speak something; for example, a cat speaks meow, dog barks
woof, etc.
Abstraction
Hiding internal details and showing functionality is known as abstraction. For example phone
call, we don't know the internal processing.
228 | P a g e
CSE,SEAT- P V RAMESH
IV SEM FSD- UNIT-4,Java Web Development 15
Encapsulation
Binding (or wrapping) code and data together into a single unit are known as encapsulation.
For example, a capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated class
because all the data members are private here.
Coupling
Cohesion
Cohesion refers to the level of a component which performs a single well-defined task. A
single well-defined task is done by a highly cohesive method. The weakly cohesive method
will split the task into separate parts. The java.io package is a highly cohesive package
because it has I/O related classes and interface. However, the java.util package is a weakly
cohesive package because it has unrelated classes and interfaces.
Association
Association represents the relationship between the objects. Here, one object can be
associated with one object or many objects. There can be four types of association between
the objects:
One to One
One to Many
Many to One, and
Many to Many
Let's understand the relationship with real-time examples. For example, One country can
have one prime minister (one to one), and a prime minister can have many ministers (one to
many). Also, many MP's can have one prime minister (many to one), and many ministers can
have many departments (many to many).
229 | P a g e
CSE,SEAT- P V RAMESH
IV SEM FSD- UNIT-4,Java Web Development 16
Aggregation
Composition
The composition is also a way to achieve Association. The composition represents the
relationship where one object contains other objects as a part of its state. There is a strong
relationship between the containing object and the dependent object. It is the state where
containing objects do not have an independent existence. If you delete the parent object, all
the child objects will be deleted automatically.
230 | P a g e
CSE,SEAT- P V RAMESH
IV SEM FSD- UNIT-4,Java Web Development 17
3) OOPs provides the ability to simulate real-world event much more effectively. We can
provide the solution of real word problem if we are using the Object-Oriented Programming
language.
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.
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.
231 | P a g e
CSE,SEAT- P V RAMESH
IV SEM FSD- UNIT-4,Java Web Development 18
Model: It represents the business layer of application. It is an object to carry the data that can
also contain the logic to update controller if data is changed.
View: It represents the presentation layer of application. It is used to visualize the data that
the model contains.
Controller: It works on both the model and view. It is used to manage the flow of
application, i.e. data flow in the model object and to update the view whenever data is
changed.
In Java Programming, the Model contains the simple Java classes, the View used to display
the data and the Controller contains the servlets. Due to this separation the user requests are
processed as follows:
1. A client (browser) sends a request to the controller on the server side, for a page.
2. The controller then calls the model. It gathers the requested data.
3. Then the controller transfers the data retrieved to the view layer.
4. Now the result is sent back to the browser (client) by the view.
MVC has the feature of scalability that in turn helps the growth of application.
The components are easy to maintain because there is less dependency.
A model can be reused by multiple views that provides reusability of code.
The developers can work with the three layers (Model, View, and Controller) simultaneously.
Using MVC, the application becomes more understandable.
Using MVC, each layer is maintained separately therefore we do not require to deal with
massive code.
The extending and testing of application is easier.
To implement MVC pattern in Java, we are required to create the following three classes.
232 | P a g e
CSE,SEAT- P V RAMESH
IV SEM FSD- UNIT-4,Java Web Development 19
The Model in the MVC design pattern acts as a data layer for the application. It represents the
business logic for application and also the state of application. The model object fetch and
store the model state in the database. Using the model layer, rules are applied to the data that
represents the concepts of application.
Let's consider the following code snippet that creates a which is also the first step to
implement MVC pattern.
Employee.java
233 | P a g e
CSE,SEAT- P V RAMESH
IV SEM FSD- UNIT-4,Java Web Development 20
34. }
The above code simply consists of getter and setter methods to the Employee class.
View Layer
As the name depicts, view represents the visualization of data received from the model. The
view layer consists of output of application or user interface. It sends the requested data to the
client, that is fetched from model layer by controller.
Let's take an example where we create a view using the EmployeeView class.
EmployeeView.java
Controller Layer
The controller layer gets the user requests from the view layer and processes them, with the
necessary validations. It acts as an interface between Model and View. The requests are then
sent to model for data processing. Once they are processed, the data is sent back to the
controller and then displayed on the view.
Let's consider the following code snippet that creates the controller using the
EmployeeController class.
EmployeeController.java
234 | P a g e
CSE,SEAT- P V RAMESH
IV SEM FSD- UNIT-4,Java Web Development 21
13.
14. // getter and setter methods
15. public void setEmployeeName(String name){
16. model.setName(name);
17. }
18.
19. public String getEmployeeName(){
20. return model.getName();
21. }
22.
23. public void setEmployeeId(String id){
24. model.setId(id);
25. }
26.
27. public String getEmployeeId(){
28. return model.getId();
29. }
30.
31. public void setEmployeeDepartment(String Department){
32. model.setDepartment(Department);
33. }
34.
35. public String getEmployeeDepartment(){
36. return model.getDepartment();
37. }
38.
39. // method to update view
40. public void updateView() {
41. view.printEmployeeDetails(model.getName(), model.getId(), model.getDepart
ment());
42. }
43. }
The following example displays the main file to implement the MVC architecture. Here, we
are using the MVCMain class.
MVCMain.java
1. // main class
2. public class MVCMain {
3. public static void main(String[] args) {
4.
5. // fetching the employee record based on the employee_id from the database
6. Employee model = retriveEmployeeFromDatabase();
7.
8. // creating a view to write Employee details on console
9. EmployeeView view = new EmployeeView();
10.
11. EmployeeController controller = new EmployeeController(model, view);
235 | P a g e
CSE,SEAT- P V RAMESH
IV SEM FSD- UNIT-4,Java Web Development 22
12.
13. controller.updateView();
14.
15. //updating the model data
16. controller.setEmployeeName("Nirnay");
17. System.out.println("\n Employee Details after updating: ");
18.
19. controller.updateView();
20. }
21.
22. private static Employee retriveEmployeeFromDatabase(){
23. Employee Employee = new Employee();
24. Employee.setName("Anu");
25. Employee.setId("11");
26. Employee.setDepartment("Salesforce");
27. return Employee;
28. }
29. }
The MVCMain class fetches the employee data from the method where we have entered the
values. Then it pushes those values in the model. After that, it initializes the view
(EmployeeView.java). When view is initialized, the Controller (EmployeeController.java) is
invoked and bind it to Employee class and EmployeeView class. At last the updateView()
method (method of controller) update the employee details to be printed to the console.
Output:
Employee Details:
Name: Anu
Employee ID: 11
Employee Department: Salesforce
In this way, we have learned about MVC Architecture, significance of each layer and its
implementation in Java.
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.
236 | P a g e
CSE,SEAT- P V RAMESH
IV SEM FSD- UNIT-4,Java Web Development 23
Model - A model contains the data of the application. A data can be a single object or a
collection of objects.
Controller - A controller contains the business logic of an application. Here, the @Controller
annotation is used to mark the class as the controller.
View - A view represents the provided information in a particular format. Generally,
JSP+JSTL is used to create a view page. Although spring also supports other view
technologies such as Apache Velocity, Thymeleaf and FreeMarker.
Front Controller - In Spring Web MVC, the DispatcherServlet class works as the front
controller. It is responsible to manage the flow of the Spring MVC application.
237 | P a g e
CSE,SEAT- P V RAMESH
IV SEM FSD- UNIT-4,Java Web Development 24
As displayed in the figure, all the incoming request is intercepted by the DispatcherServlet
that works as the front controller.
The DispatcherServlet gets an entry of handler mapping from the XML file and forwards the
request to the controller.
The controller returns an object of ModelAndView.
The DispatcherServlet checks the entry of view resolver in the XML file and invokes the
specified view component.
Separate roles - The Spring MVC separates each role, where the model object, controller,
command object, view resolver, DispatcherServlet, validator, etc. can be fulfilled by a
specialized object.
Light-weight - It uses light-weight servlet container to develop and deploy your application.
Powerful Configuration - It provides a robust configuration for both framework and
application classes that includes easy referencing across contexts, such as from web
controllers to business objects and validators.
Rapid development - The Spring MVC facilitates fast and parallel development.
Reusable business code - Instead of creating new objects, it allows us to use the existing
business objects.
Easy to test - In Spring, generally we create JavaBeans classes that enable you to inject test
data using the setter methods.
Flexible Mapping - It provides the specific annotations that easily redirect the page.
Load the spring jar files or add dependencies in the case of Maven
Create the controller class
Provide the entry of controller in the web.xml file
Define the bean in the separate XML file
Display the message in the JSP page
Start the server and deploy the project
238 | P a g e
CSE,SEAT- P V RAMESH
IV SEM FSD- UNIT-4,Java Web Development 25
239 | P a g e
CSE,SEAT- P V RAMESH
IV SEM FSD- UNIT-4,Java Web Development 26
Download Link:Download all the jar files for spring including JSP and JSTL.
If you are using Maven, you don't need to add jar files. Now, you need to add maven
dependency to the pom.xml file.
pom.xml
240 | P a g e
CSE,SEAT- P V RAMESH
IV SEM FSD- UNIT-4,Java Web Development 27
To create the controller class, we are using two annotations @Controller and
@RequestMapping.
The @Requestmapping annotation is used to map the class with the specified URL name.
HelloController.java
1. package com.javatpoint;
2. import org.springframework.stereotype.Controller;
3. import org.springframework.web.bind.annotation.RequestMapping;
4. @Controller
5. public class HelloController {
6. @RequestMapping("/")
7. public String display()
8. {
9. return "index";
10. }
11. }
In this xml file, we are specifying the servlet class DispatcherServlet that acts as the front
controller in Spring Web MVC. All the incoming request for the html file will be forwarded
to the DispatcherServlet.
web.xml
This is the important configuration file where we need to specify the View components.
241 | P a g e
CSE,SEAT- P V RAMESH
IV SEM FSD- UNIT-4,Java Web Development 28
spring-servlet.xml
This is the simple JSP page, displaying the message returned by the Controller.
index.jsp
1. <html>
2. <body>
3. <p>Welcome to Spring MVC Tutorial</p>
4. </body>
5. </html>
Output:
242 | P a g e
CSE,SEAT- P V RAMESH
IV SEM FSD- UNIT-4,Java Web Development 29
There’s a much larger discussion to be had about how REST fits in the world of
microservices, but — for this tutorial — let’s just look at building RESTful services.
Why REST? REST embraces the precepts of the web, including its architecture, benefits, and
everything else. This is no surprise given its author, Roy Fielding, was involved in probably a
dozen specs which govern how the web operates.
What benefits? The web and its core protocol, HTTP, provide a stack of features:
These are all critical factors on building resilient services. But that is not all. The web is built
out of lots of tiny specs, hence it’s been able to evolve easily, without getting bogged down in
"standards wars".
Developers are able to draw upon 3rd party toolkits that implement these diverse specs and
243 | P a g e
CSE,SEAT- P V RAMESH
IV SEM FSD- UNIT-4,Java Web Development 30
What’s important to realize is that REST, however ubiquitous, is not a standard, per se, but
an approach, a style, a set of constraints on your architecture that can help you build web-
scale systems. In this tutorial we will use the Spring portfolio to build a RESTful service
while leveraging the stackless features of REST.
Getting Started
As we work through this tutorial, we’ll use Spring Boot. Go to Spring Initializr and add the
following dependencies to a project:
Web
JPA
H2
Change the Name to "Payroll" and then choose "Generate Project". A .zip will download.
Unzip it. Inside you’ll find a simple, Maven-based project including a pom.xml build file
(NOTE: You can use Gradle. The examples in this tutorial will be Maven-based.)
Spring Boot can work with any IDE. You can use Eclipse, IntelliJ IDEA, Netbeans, etc. The
Spring Tool Suite is an open-source, Eclipse-based IDE distribution that provides a superset
of the Java EE distribution of Eclipse. It includes features that make working with Spring
applications even easier. It is, by no means, required. But consider it if you want that extra
oomph for your keystrokes. Here’s a video demonstrating how to get started with STS and
Spring Boot. This is a general introduction to familiarize you with the tools.
Big picture: We’re going to create a simple payroll service that manages the employees of a
company. We’ll store employee objects in a (H2 in-memory) database, and access them (via
something called JPA). Then we’ll wrap that with something that will allow access over the
internet (called the Spring MVC layer).
244 | P a g e
CSE,SEAT- P V RAMESH
IV SEM FSD- UNIT-4,Java Web Development 31
nonrest/src/main/java/payroll/Employee.java
package payroll;
importjava.util.Objects;
importjavax.persistence.Entity;
importjavax.persistence.GeneratedValue;
importjavax.persistence.Id;
@Entity
classEmployee{
private@Id@GeneratedValueLong id;
privateString name;
privateString role;
Employee(){}
this.name = name;
this.role= role;
}
publicLonggetId(){
returnthis.id;
}
publicStringgetName(){
returnthis.name;
}
publicStringgetRole(){
returnthis.role;
}
publicvoidsetId(Long id){
this.id = id;
}
publicvoidsetName(String name){
this.name = name;
}
publicvoidsetRole(String role){
this.role= role;
}
@Override
publicbooleanequals(Object o){
if(this== o)
returntrue;
if(!(o instanceofEmployee))
returnfalse;
Employeeemployee=(Employee) o;
returnObjects.equals(this.id, employee.id)&&Objects.equals(this.name, employee.name)
&&Objects.equals(this.role,employee.role);
}
245 | P a g e
CSE,SEAT- P V RAMESH
IV SEM FSD- UNIT-4,Java Web Development 32
@Override
publicinthashCode(){
returnObjects.hash(this.id,this.name,this.role);
}
@Override
publicStringtoString(){
return"Employee{"+"id="+this.id +", name='"+this.name +'\''+", role='"+this.role+'\''+'}';
}
}
@Entity is a JPA annotation to make this object ready for storage in a JPA-based data
store.
id, name, and role are attributes of our Employee domain object. id is marked with more
JPA annotations to indicate it’s the primary key and automatically populated by the
JPA provider.
a custom constructor is created when we need to create a new instance, but don’t yet
have an id.
With this domain object definition, we can now turn to Spring Data JPA to handle the tedious
database interactions.
Spring Data JPA repositories are interfaces with methods supporting creating, reading,
updating, and deleting records against a back end data store. Some repositories also support
data paging, and sorting, where appropriate. Spring Data synthesizes implementations based
on conventions found in the naming of the methods in the interface.
There are multiple repository implementations besides JPA. You can use Spring Data MongoDB,
Spring Data GemFire, Spring Data Cassandra, etc. For this tutorial, we’ll stick with JPA.
Spring makes accessing data easy. By simply declaring the following EmployeeRepository
interface we automatically will be able to
nonrest/src/main/java/payroll/EmployeeRepository.java
package payroll;
importorg.springframework.data.jpa.repository.JpaRepository;
interfaceEmployeeRepositoryextendsJpaRepository<Employee,Long>{
To get all this free functionality, all we had to do was declare an interface which extends
246 | P a g e
CSE,SEAT- P V RAMESH
IV SEM FSD- UNIT-4,Java Web Development 33
Spring Data JPA’s JpaRepository, specifying the domain type as Employee and the id type as
Long.
Spring Data’s repository solution makes it possible to sidestep data store specifics and instead
solve a majority of problems using domain-specific terminology.
Believe it or not, this is enough to launch an application! A Spring Boot application is, at a
minimum, a public static void main entry-point and the @SpringBootApplication annotation. This
tells Spring Boot to help out, wherever possible.
nonrest/src/main/java/payroll/PayrollApplication.java
package payroll;
importorg.springframework.boot.SpringApplication;
importorg.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
publicclassPayrollApplication{
publicstaticvoidmain(String...args){
SpringApplication.run(PayrollApplication.class,args);
}
}
Nevertheless, an application with no data isn’t very interesting, so let’s preload it. The
following class will get loaded automatically by Spring:
nonrest/src/main/java/payroll/LoadDatabase.java
package payroll;
importorg.slf4j.Logger;
importorg.slf4j.LoggerFactory;
importorg.springframework.boot.CommandLineRunner;
importorg.springframework.context.annotation.Bean;
importorg.springframework.context.annotation.Configuration;
@Configuration
classLoadDatabase{
@Bean
CommandLineRunnerinitDatabase(EmployeeRepository repository){
returnargs->{
log.info("Preloading "+repository.save(newEmployee("Bilbo Baggins","burglar")));
log.info("Preloading "+repository.save(newEmployee("Frodo Baggins","thief")));
};
}
}
247 | P a g e
CSE,SEAT- P V RAMESH
IV SEM FSD- UNIT-4,Java Web Development 34
Spring Boot will run ALL CommandLineRunner beans once the application context is
loaded.
This runner will request a copy of the EmployeeRepository you just created.
Using it, it will create two entities and store them.
This isn’t the whole log, but just the key bits of preloading data. (Indeed, check out the whole
console. It’s glorious.)
nonrest/src/main/java/payroll/EmployeeController.java
package payroll;
importjava.util.List;
importorg.springframework.web.bind.annotation.DeleteMapping;
importorg.springframework.web.bind.annotation.GetMapping;
importorg.springframework.web.bind.annotation.PathVariable;
importorg.springframework.web.bind.annotation.PostMapping;
importorg.springframework.web.bind.annotation.PutMapping;
importorg.springframework.web.bind.annotation.RequestBody;
importorg.springframework.web.bind.annotation.RestController;
@RestController
classEmployeeController{
privatefinalEmployeeRepository repository;
EmployeeController(EmployeeRepository repository){
this.repository= repository;
}
// Aggregate root
// tag::get-aggregate-root[]
@GetMapping("/employees")
List<Employee>all(){
returnrepository.findAll();
248 | P a g e
CSE,SEAT- P V RAMESH
IV SEM FSD- UNIT-4,Java Web Development 35
}
// end::get-aggregate-root[]
@PostMapping("/employees")
EmployeenewEmployee(@RequestBodyEmployeenewEmployee){
returnrepository.save(newEmployee);
}
// Single item
@GetMapping("/employees/{id}")
Employeeone(@PathVariableLong id){
returnrepository.findById(id)
.orElseThrow(()->newEmployeeNotFoundException(id));
}
@PutMapping("/employees/{id}")
EmployeereplaceEmployee(@RequestBodyEmployeenewEmployee,@PathVariableLong id){
returnrepository.findById(id)
.map(employee ->{
employee.setName(newEmployee.getName());
employee.setRole(newEmployee.getRole());
returnrepository.save(employee);
})
.orElseGet(()->{
newEmployee.setId(id);
returnrepository.save(newEmployee);
});
}
@DeleteMapping("/employees/{id}")
voiddeleteEmployee(@PathVariableLong id){
repository.deleteById(id);
}
}
@RestController indicates that the data returned by each method will be written straight
into the response body instead of rendering a template.
An EmployeeRepository is injected by constructor into the controller.
We have routes for each operation (@GetMapping, @PostMapping, @PutMapping and
@DeleteMapping, corresponding to HTTP GET, POST, PUT, and DELETE calls). (NOTE:
It’s useful to read each method and understand what they do.)
EmployeeNotFoundException is an exception used to indicate when an employee is looked
up but not found.
nonrest/src/main/java/payroll/EmployeeNotFoundException.java
package payroll;
classEmployeeNotFoundExceptionextendsRuntimeException{
EmployeeNotFoundException(Long id){
super("Could not find employee "+ id);
}
}
249 | P a g e
CSE,SEAT- P V RAMESH
IV SEM FSD- UNIT-4,Java Web Development 36
nonrest/src/main/java/payroll/EmployeeNotFoundAdvice.java
package payroll;
importorg.springframework.http.HttpStatus;
importorg.springframework.web.bind.annotation.ControllerAdvice;
importorg.springframework.web.bind.annotation.ExceptionHandler;
importorg.springframework.web.bind.annotation.ResponseBody;
importorg.springframework.web.bind.annotation.ResponseStatus;
@ControllerAdvice
classEmployeeNotFoundAdvice{
@ResponseBody
@ExceptionHandler(EmployeeNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
StringemployeeNotFoundHandler(EmployeeNotFoundException ex){
returnex.getMessage();
}
}
@ResponseBody signals that this advice is rendered straight into the response body.
@ExceptionHandler configures the advice to only respond if an EmployeeNotFoundException
is thrown.
@ResponseStatus says to issue an HttpStatus.NOT_FOUND, i.e. an HTTP 404.
The body of the advice generates the content. In this case, it gives the message of the
exception.
To launch the application, either right-click the public static void main in PayRollApplication and
select Run from your IDE, or:
$ curl -v localhost:8080/employees
* Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 8080 (#0)
> GET /employees HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.54.0
250 | P a g e
CSE,SEAT- P V RAMESH
IV SEM FSD- UNIT-4,Java Web Development 37
$ curl -v localhost:8080/employees/99
You get…
* Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 8080 (#0)
> GET /employees/99 HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.54.0
> Accept: */*
>
< HTTP/1.1 404
< Content-Type: text/plain;charset=UTF-8
< Content-Length: 26
< Date: Thu, 09 Aug 2018 18:00:56 GMT
<
* Connection #0 to host localhost left intact
Could not find employee 99
This message nicely shows an HTTP 404 error with the custom message Could not find
employee 99.
If you are using Windows Command Prompt to issue cURL commands, chances are the
below command won’t work properly. You must either pick a terminal that support single
quoted arguments, or use double quotes and then escape the ones inside the JSON.
To create a new Employee record we use the following command in a terminal—the $ at the
beginning signifies that what follows it is a terminal command:
{"id":3,"name":"Samwise Gamgee","role":"gardener"}
251 | P a g e
CSE,SEAT- P V RAMESH
IV SEM FSD- UNIT-4,Java Web Development 38
This is all well and good, but do we have a RESTful service yet? (If you didn’t catch the hint,
the answer is no.)
What’s missing?
In fact, what we have built so far is better described as RPC (Remote Procedure Call).
That’s because there is no way to know how to interact with this service. If you published this
today, you’d also have to write a document or host a developer’s portal somewhere with all
the details.
This statement of Roy Fielding’s may further lend a clue to the difference between REST
and RPC:
I am getting frustrated by the number of people calling any HTTP-based interface a REST
API. Today’s example is the SocialSite REST API. That is RPC. It screams RPC. There is so
much coupling on display that it should be given an X rating.
What needs to be done to make the REST architectural style clear on the notion that hypertext
is a constraint? In other words, if the engine of application state (and hence the API) is not
being driven by hypertext, then it cannot be RESTful and cannot be a REST API. Period. Is
252 | P a g e
CSE,SEAT- P V RAMESH
IV SEM FSD- UNIT-4,Java Web Development 39
— Roy Fielding
https://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven
The side effect of NOT including hypermedia in our representations is that clients MUST
hard code URIs to navigate the API. This leads to the same brittle nature that predated the
rise of e-commerce on the web. It’s a signal that our JSON output needs a little help.
Introducing Spring HATEOAS, a Spring project aimed at helping you write hypermedia-
driven outputs. To upgrade your service to being RESTful, add this to your build:
This tiny library will give us the constructs to define a RESTful service and then render it in
an acceptable format for client consumption.
A critical ingredient to any RESTful service is adding links to relevant operations. To make
your controller more RESTful, add links like this:
Employeeemployee=repository.findById(id)//
.orElseThrow(()->newEmployeeNotFoundException(id));
returnEntityModel.of(employee,//
linkTo(methodOn(EmployeeController.class).one(id)).withSelfRel(),
linkTo(methodOn(EmployeeController.class).all()).withRel("employees"));
}
This tutorial is based on Spring MVC and uses the static helper methods from
WebMvcLinkBuilder to build these links. If you are using Spring WebFlux in your project, you
must instead use WebFluxLinkBuilder.
This is very similar to what we had before, but a few things have changed:
The return type of the method has changed from Employee to EntityModel<Employee>.
EntityModel<T> is a generic container from Spring HATEOAS that includes not only
the data but a collection of links.
linkTo(methodOn(EmployeeController.class).one(id)).withSelfRel() asks that Spring HATEOAS
build a link to the EmployeeController 's one() method, and flag it as a self link.
linkTo(methodOn(EmployeeController.class).all()).withRel("employees") asks Spring HATEOAS
to build a link to the aggregate root, all(), and call it "employees".
What do we mean by "build a link"? One of Spring HATEOAS’s core types is Link. It
includes a URI and a rel (relation). Links are what empower the web. Before the World Wide
253 | P a g e
CSE,SEAT- P V RAMESH
IV SEM FSD- UNIT-4,Java Web Development 40
Web, other document systems would render information or links, but it was the linking of
documents WITH this kind of relationship metadata that stitched the web together.
Roy Fielding encourages building APIs with the same techniques that made the web
successful, and links are one of them.
If you restart the application and query the employee record of Bilbo, you’ll get a slightly
different response than earlier:
Curling prettier
When your curl output gets more complex it can become hard to read. Use this or other tips
to prettify the json returned by curl:
# The indicated part pipes the output to json_pp and asks it to make your JSON pretty. (Or use whatever tool
you like!)
# v------------------v
curl -v localhost:8080/employees/1 | json_pp
RESTful representation of a single employee
{
"id":1,
"name":"Bilbo Baggins",
"role":"burglar",
"_links":{
"self":{
"href":"http://localhost:8080/employees/1"
},
"employees":{
"href":"http://localhost:8080/employees"
}
}
}
This decompressed output shows not only the data elements you saw earlier ( id, name and
role), but also a _links entry containing two URIs. This entire document is formatted using
HAL.
HAL is a lightweight mediatype that allows encoding not just data but also hypermedia
controls, alerting consumers to other parts of the API they can navigate toward. In this case,
there is a "self" link (kind of like a this statement in code) along with a link back to the
aggregate root.
To make the aggregate root ALSO more RESTful, you want to include top level links while
ALSO including any RESTful components within.
So we turn this
254 | P a g e
CSE,SEAT- P V RAMESH
IV SEM FSD- UNIT-4,Java Web Development 41
into this
returnCollectionModel.of(employees,linkTo(methodOn(EmployeeController.class).all()).withSelfRel());
}
Wow! That method, which used to just be repository.findAll(), is all grown up! Not to worry.
Let’s unpack it.
Project Object Model (POM) is an XML file that contains the java project details,
configurations, and settings required for maven to build the project.
The pom.xml file is present in the root of the java project directory. Primarily it contains the
project dependencies.
So when you build the code with maven, it reads the pom.xml file and downloads all the
dependencies from the maven repository. Dependencies could be third-party libraries from
the public Maven Repository or common libraries hosted within an organization’s private
maven repository. You can compare it with Python pip, Nodejs npm, or Ruby gems
By default, maven uses the public repository but if you have in-house private maven
repositories, you configure custom maven repository URLs in settings.xml maven configuration
present in the maven installation directory. for example, /opt/apache-maven-3.8.6/conf/settings.xml
255 | P a g e
CSE,SEAT- P V RAMESH
IV SEM FSD- UNIT-4,Java Web Development 42
Maven Prerequisites
For maven to work you need the following installed on your system
1. Java JDK
2. Maven
To install and configure JDK and maven, follow the maven installation guide.
The code base has the following important folders and files. It is common in real-time project
code as well.
1. /src folder: This folder contains the source code based on the java spring framework.
2. /src/tests folder: This folder contains the unit tests & integration tests of the code under the
tests folder.
3. pom.xml file: It contains all the dependencies required for the pet-clinic applications. As it is
an open-source application, all the dependencies are from the public maven repository.
To build the project, cd into the project root directory. In my case its spring-petclinic. It should
contain the pom.xml file
cd spring-petclinic
From a CI perspective, we just have to build, test, and package the project to create a
deployable artifact(jar file)
So commonly in the CI process, we build and package the java projects using the following
maven command. It compiles the code, tests it, package it as a jar file in the target folder, and
will also install(copy) the jar package in the local .m2 repository.
After executing the above command, you will see a folder named target in the root directory.
Inside the target directory, you will see the packaged jar file as shown below. We call it a
deployable artifact.
256 | P a g e
CSE,SEAT- P V RAMESH
IV SEM FSD- UNIT-4,Java Web Development 43
Even time you run mvn clean install, it deletes target directory and packages from the local .m2
repository and replaces it with the latest build files and packages.
If you want to skip the test during build, you can add the -Dmaven.test.skip=true parameter as
shown below.
Now that you have understood how to build a java project using maven, let’s look into the
maven lifecycle. Few commands we don’t have to use in the CI pipelines. However, it is
good to know about the maven lifecycle commands and you can use them depending on your
CI pipeline requirement.
mvn validate validates the maven project. It downloads all the required dependencies to the
257 | P a g e
CSE,SEAT- P V RAMESH
IV SEM FSD- UNIT-4,Java Web Development 44
mvn compile compiles the java project. It runs validate first and then compiles the code.
mvn test command runs the unit test that is part of the code. You can test classes individually,
methods individually, or add patterns to run tests on all methods that match the pattern.
mvn package commands compile the code, test it and finally package it in the required format
(jar or war)
mvn verify command runs all the phases explained before in order and runs checks on
integration tests and checkstyles if they are defined in the project.
mvn install command installs the packaged code in the local maven repository.
mvn deploy command, deploys the package to the remote maven repository. When you run
deploy, it first runs validate, compile, test, package, verify, install, and then finally deploys
the package to the remote maven repository.
If maven doesn’t support the Java version, you will get the above error.
To rectify it, install the latest maven version that supports the installed Java version.
If you try to execute the maven command from the location where there is no pom.xml file,
258 | P a g e
CSE,SEAT- P V RAMESH
IV SEM FSD- UNIT-4,Java Web Development 45
The goal you specified requires a project to execute but there is no POM in this directory
To rectify this, execute the maven command from the folder that has the pom.xml file.
Yes. By default, the mvn package command runs the test. However, you can add the flag -
Dmaven.test.skip to skip the tests.
mvn test runs all the unit tests for the java project.
Conclusion
As a Devops engineer, it is very important to understand the java build process if you are
working on deploying java projects.
259 | P a g e
CSE,SEAT- P V RAMESH