Unit 4 1 FSD Cse
Unit 4 1 FSD Cse
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
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.
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:
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'.
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.
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
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).
You will be able to see ' Hello World ' printed on the window.
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.
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.
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.
Java Modifiers
Like other languages, it is possible to modify classes, methods, etc., by using modifiers. There are two categories of
modifiers:
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 {
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.
8
Java
short static strictfp super
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.
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.
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:
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 {
Example 2
Following implementation shows a classic Singleton design pattern:
public class ClassicSingleton {
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:
Initialization: The 'new' keyword is followed by a call to a constructor. This callinitializes the new object.
Example
This example explains how to access instance variables and methods of a class.
public class
Puppy{
int puppyAge;
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.
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
StudentView.java
StudentController.java
MVCPatternDemo.java
public class MVCPatternDemo {
public static void main(String[] args) {
controller.updateView();
controller.updateView();
}
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 −
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 −
<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...>
<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>
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.
<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.
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.
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.
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.
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:
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.
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:
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.
mvn -version
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.