Java Unit V
Java Unit V
UNIT-5
Spring Framework
It was developed by Rod Johnson in 2003. Spring framework makes the easy
development of JavaEE application.
The Spring framework comprises several modules such as IOC, AOP, DAO, Context, ORM,
WEB MVC etc. We will learn these modules in next page. Let's understand the IOC and
Dependency Injection first.
These are the design patterns that are used to remove dependency from the
programming code. They make the code easier to test and maintain. Let's understand this
with the following code:
class Employee{
Address address;
Employee()
{
address=new Address();
}}
In such case, there is dependency between the Employee and Address (tight coupling). In
the Inversion of Control scenario, we do this something like this:
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]
class Employee{
Address address;
Employee(Address address)
{
this.address=address;
}}
Thus, IOC makes the code loosely coupled. In such case, there is no need to modify the
code if our logic is moved to new environment.
Example-2
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]
1) Predefined Templates
o Spring framework provides templates for JDBC, Hibernate, JPA etc. technologies.
So there is no need to write too much code. It hides the basic steps of these technologies.
o Let's take the example of JdbcTemplate, you don't need to write the code for
exception handling, creating connection, creating statement, committing transaction,
closing connection etc. You need to write the code of executing query only. Thus, it save
a lot of JDBC code.
2) Loose Coupling
3) Easy to test
o The Dependency Injection makes easier to test the application. The EJB or Struts
application require server to run the application but Spring framework doesn't require
server.
4) Lightweight
5) Fast Development
6) Powerful abstraction
7) Declarative support
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]
Test
This layer provides support of testing with JUnit and TestNG.
Spring Core Container
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]
The Spring Core container contains core, beans, context and expression language (EL)
modules.
Core and Beans
These modules provide IOC and Dependency Injection features.
Context
This module supports internationalization (I18N), EJB, JMS, Basic Remoting.
Expression Language
It is an extension to the EL defined in JSP. It provides support to setting and getting
property values, method invocation, accessing collections and indexers, named variables,
logical and arithmetic operators, retrieval of objects by name etc.
AOP, Aspects and Instrumentation
These modules support aspect oriented programming implementation where you can use
Advices, Pointcuts etc. to decouple the code.
The aspects module provides support to integration with AspectJ.
The instrumentation module provides support to class instrumentation and classloader
implementations.
Data Access / Integration
This group comprises of JDBC, ORM, OXM, JMS and Transaction modules. These modules
basically provide support to interact with the database.
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]
package myspring;
public class Student
{
private String name;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]
{
System.out.println("Hello: "+name);
}
}
This is simple bean class, containing only one property name with its getters and setters
method. This class contains one extra method named displayInfo() that prints the
student name by the hello message.
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
</beans>
The bean element is used to define the bean for the given class.
The property subelement of bean specifies the property of the Student class named
name. The value specified in the property element will be set in the Student class object
by the IOC container.
Create the java class e.g. Test. Here we are getting the object of Student class from the
IOC container using the getBean() method of BeanFactory. Let's see the code of test class.
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]
Package myspring;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
Student student=(Student)factory.getBean("studentbean");
student.displayInfo();
}
}
There are mainly three jar files required to run this application.
o org.springframework.core-3.0.1.RELEASE-A
o com.springsource.org.apache.commons.logging-1.1.1
o org.springframework.beans-3.0.1.RELEASE-A
For the future use, You can download the required jar files for spring core application.
5) Run the test class
Now run the Test class. You will get the output Hello: Dhara Singh
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]
IoC Container
The IoC container is responsible to instantiate, configure and assemble the objects. The
IoC container gets informations from the XML file and works accordingly. The main tasks
performed by IoC container are:
1. BeanFactory
2. ApplicationContext
Using BeanFactory
The XmlBeanFactory is the implementation class for the BeanFactory interface. To use the
BeanFactory, we need to create the instance of XmlBeanFactory class as given below:
The constructor of XmlBeanFactory class receives the Resource object so we need to pass
the resource object to create the object of BeanFactory.
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]
Using ApplicationContext
Dependency Lookup
The Dependency Lookup is an approach where we get the resource after demand. There
can be various ways to get the resource for example:
In such way, we get the resource(instance of A class) directly by new keyword. Another
way is factory method:
A obj = A.getA();
This way, we get the resource (instance of A class) by calling the static factory method
getA().
Alternatively, we can get the resource by JNDI (Java Naming Directory Interface) as:
A obj = (A)environmentCtx.lookup("A");
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]
There can be various ways to get the resource to obtain the resource. Let's see the
problem in this approach.
o tight coupling The dependency lookup approach makes the code tightly coupled.
If resource is changed, we need to perform a lot of modification in the code.
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]
o Not easy for testing This approach creates a lot of problems while testing the
application especially in black box testing.
Dependency Injection
The Dependency Injection is a design pattern that removes the dependency of the
programs. In such case we provide the information from the external source such as XML
file. It makes our code loosely coupled and easier for testing. In such case we write the
code as:
class Employee{
Address address;
Employee(Address address){
this.address=address;
}
public void setAddress(Address address){
this.address=address;
}
In such case, instance of Address class is provided by external souce such as XML file
either by constructor or setter method.
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]
simple example to inject primitive and string-based values. We have created three files
here:
o Employee.java
o applicationContext.xml
o Test.java
Employee.java
It is a simple class containing two fields id and name. There are four constructors and one
method in this class.
package myspring;
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]
applicationContext.xml
We are providing the information into the bean by this file. The constructor-arg element
invokes the constructor. In such case, parameterized constructor of int type will be
invoked. The value attribute of constructor-arg element will assign the specified value.
The type attribute specifies that int parameter constructor will be invoked.
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
</bean>
</beans>
Test.java
This class gets the bean from the applicationContext.xml file and calls the show method.
package myspring;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.*;
Employee s=(Employee)factory.getBean("e");
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]
s.show();
}
}
If there is HAS-A relationship between the classes, we create the instance of dependent
object (contained object) first then pass it as an argument of the main class constructor.
Here, our scenario is Employee HAS-A Address. The Address class object will be termed
as the dependent object. Let's see the Address class first:
Address.java
This class contains three properties, one constructor and toString() method to return the
values of these object.
package myspring;
Employee.java
It contains three properties id, name and address(dependent object) ,two constructors
and show() method to show the records of the current object including the depedent
object.
package myspring;
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]
void show(){
System.out.println(id+" "+name);
System.out.println(address.toString());
}
applicationContext.xml
The ref attribute is used to define the reference of another object, such way we are
passing the dependent object as an constructor argument.
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]
<constructor-arg value="ghaziabad"></constructor-arg>
<constructor-arg value="UP"></constructor-arg>
<constructor-arg value="India"></constructor-arg>
</bean>
</beans>
Test.java
This class gets the bean from the applicationContext.xml file and calls the show method.
package myspring;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.*;
Employee s=(Employee)factory.getBean("e");
s.show();
}
}
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]
o Employee.java
o applicationContext.xml
o Test.java
Employee.java
It is a simple class containing three fields id, name and city with its setters and getters and
a method to display these informations.
package myspring;
public class Employee {
private int id;
private String name;
private String city;
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]
}
public void setCity(String city) {
this.city = city;
}
void display(){
System.out.println(id+" "+name+" "+city);
}
applicationContext.xml
We are providing the information into the bean by this file. The property element invokes
the setter method. The value subelement of property will assign the specified value.
</bean>
</beans>
Test.java
This class gets the bean from the applicationContext.xml file and calls the display method.
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]
package myspring;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.*;
Employee e=(Employee)factory.getBean("obj");
s.display();
}
}
What is AOP
One of the key components of Spring Framework is the Aspect oriented programming
(AOP) framework. Aspect-Oriented Programming entails breaking down program logic into
distinct parts called so-called concerns. The functions that span multiple points of an application
are called cross-cutting concerns and these cross-cutting concerns are conceptually separate
from the application's business logic. There are various common good examples of aspects like
logging, auditing, declarative transactions, security, caching, etc.
The key unit of modularity in OOP is the class, whereas in AOP the unit of modularity is the
aspect. Dependency Injection helps you decouple your application objects from each other and
AOP helps you decouple cross-cutting concerns from the objects that they affect. AOP is like
triggers in programming languages such as Perl, .NET, Java, and others.
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]
AOP Terminologies
These terms are not specific to Spring, rather they are related to AOP.
1
Aspect
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]
This is a module which has a set of APIs providing cross-cutting requirements. For
example, a logging module would be called AOP aspect for logging. An application can
have any number of aspects depending on the requirement.
Join point
This represents a point in your application where you can plug-in the AOP aspect. You
2
can also say, it is the actual place in the application where an action will be taken using
Spring AOP framework.
Advice
This is the actual action to be taken either before or after the method execution. This is an
3
actual piece of code that is invoked during the program execution by Spring AOP
framework.
Pointcut
4 This is a set of one or more join points where an advice should be executed. You can
specify pointcuts using expressions or patterns as we will see in our AOP examples.
Introduction
5
An introduction allows you to add new methods or attributes to the existing classes.
Target object
6 The object being advised by one or more aspects. This object will always be a proxied
object, also referred to as the advised object.
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]
Weaving
Weaving is the process of linking aspects with other application types or objects to create
an advised object. This can be done at compile time, load time, or at runtime.
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]
request Scopes a single bean definition to the lifecycle of a single HTTP request. That is,
each HTTP request has its own instance of a bean created off the back of a single
bean definition. Only valid in the context of a web-aware
Spring ApplicationContext.
session Scopes a single bean definition to the lifecycle of an HTTP Session. Only valid in
the context of a web-aware Spring ApplicationContext.
application Scopes a single bean definition to the lifecycle of a ServletContext. Only valid in
the context of a web-aware Spring ApplicationContext.
websocket Scopes a single bean definition to the lifecycle of a WebSocket. Only valid in the
context of a web-aware Spring ApplicationContext.
If a scope is set to singleton, the Spring IoC container creates exactly one instance of the object
defined by that bean definition. This single instance is stored in a cache of such singleton beans,
and all subsequent requests and references for that named bean return the cached object.
The default scope is always singleton. However, when you need one and only one instance of a
bean, you can set the scope property to singleton in the bean configuration file, as shown in the
following code snippet −
package myspring;
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]
MainApp.java file −
package myspring;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]
Auto wiring
• It is the feature of spring frame work by which we can achieved
“DI automatically.” or in other words we can say that Features of
spring framework in which spring container inject the
dependencies automatically.
• Autowiring can not be used to inject primitive and string values. It
work with reference only.
• Suppose we have two classes A and B. A needs to object of class
B.
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]
By XML file
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
</beans>
2. By Annotation
• Using @Autowired
Used with 3 places
1. Used with Property
2. Used with Setter Method
3. Used with Constructor
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]
Java Annotations
Java Annotation is a tag that represents the metadata i.e. attached with class, interface,
methods or fields to indicate some additional information which can be used by java
compiler and JVM.
First, we will learn some built-in annotations then we will move on creating and using
custom annotations.
@Override annotation assures that the subclass method is overriding the parent class
method. If it is not so, compile time error occurs.
Sometimes, we does the silly mistake such as spelling mistakes etc. So, it is better to mark
@Override annotation that provides assurity that method is overridden.
class Animal{
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]
class TestAnnotation1{
public static void main(String args[]){
Animal a=new Dog();
a.eatSomething();
}}
@SuppressWarnings
@SuppressWarnings annotation: is used to suppress warnings issued by the compiler.
import java.util.*;
class TestAnnotation2{
@SuppressWarnings("unchecked")
public static void main(String args[]){
ArrayList list=new ArrayList();
list.add("sonoo");
list.add("vimal");
list.add("ratan");
for(Object obj:list)
System.out.println(obj);
}}
@Deprecated
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]
class A{
void m(){System.out.println("hello m");}
@Deprecated
void n(){System.out.println("hello n");}
}
class TestAnnotation3{
public static void main(String args[]){
A a=new A();
a.n();
}}
At Compile Time:
Note: Test.java uses or overrides a deprecated API.
Java Custom annotations or Java User-defined annotations are easy to create and use.
The @interface element is used to declare an annotation. For example:
@interface MyAnnotation{}
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]
Types of Annotation
1. Marker Annotation
2. Single-Value Annotation
3. Multi-Value Annotation
1) Marker Annotation
ADVERTISEMENT
@interface MyAnnotation{}
2) Single-Value Annotation
An annotation that has one method, is called single-value annotation. For example:
@interface MyAnnotation{
int value();
}
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]
@interface MyAnnotation{
int value() default 0;
}
How to apply Single-Value Annotation
@MyAnnotation(value=10)
3) Multi-Value Annotation
An annotation that has more than one method, is called Multi-Value annotation. For
example:
@interface MyAnnotation{
int value1();
String value2();
String value3();
}}
We can provide the default value also. For example:
@interface MyAnnotation{
int value1() default 1;
String value2() default "";
String value3() default "xyz";
}
How to apply Multi-Value Annotation
@MyAnnotation(value1=10,value2="Arun Kumar",value3="Ghaziabad")
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]
Spring Boot is a project that is built on the top of the Spring Framework. It provides an
easier and faster way to set up, configure, and run both simple and web-based
applications.
It is a Spring module that provides the RAD (Rapid Application Development) feature
to the Spring Framework. It is used to create a stand-alone Spring-based application that
you can just run because it needs minimal Spring configuration.
In short, Spring Boot is the combination of Spring Framework and Embedded Servers.
We can use Spring STS IDE or Spring Initializr to develop Spring Boot Java applications.
o Spring Data: It simplifies data access from the relational and NoSQL databases.
o Spring Batch: It provides powerful batch processing.
o Spring Security: It is a security framework that provides robust security to applications.
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]
o SpringApplication
o Application events and listeners
o Admin features
o Externalized Configuration
o Properties Files
o YAML Support
o Type-safe Configuration
o Logging
o Security
Spring Framework is a widely used Java EE Spring Boot Framework is widely used to
framework for building applications. develop REST APIs.
It aims to simplify Java EE development that It aims to shorten the code length and provide
makes developers more productive. the easiest way to develop Web Applications.
The primary feature of the Spring Framework The primary feature of Spring Boot
is dependency injection. is Autoconfiguration. It automatically
configures the classes based on the requirement.
It helps to make things simpler by allowing us It helps to create a stand-alone application with
to develop loosely coupled applications. less configuration.
To test the Spring project, we need to set up the Spring Boot offers embedded server such
sever explicitly. as Jetty and Tomcat, etc.
It does not provide support for an in-memory It offers several plugins for working with an
database. embedded and in-memory database such
as H2.
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]
It reduces development time and increases It takes more time to achieve the
productivity. same.
o Presentation Layer
o Business Layer
o Persistence Layer
o Database Layer
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]
Presentation Layer: The presentation layer handles the HTTP requests, translates the
JSON parameter to object, and authenticates the request and transfer it to the business
layer. In short, it consists of views i.e., frontend part.
Business Layer: The business layer handles all the business logic. It consists of service
classes and uses services provided by data access layers. It also
performs authorization and validation.
Persistence Layer: The persistence layer contains all the storage logic and translates
business objects from and to database rows.
Database Layer: In the database layer, CRUD (create, retrieve, update, delete) operations
are performed.
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]
Default package
A class that does not have any package declaration is considered as a default
package. Note that generally a default package declaration is not recommended.
Spring Boot will cause issues such as malfunctioning of Auto Configuration or
Component Scan, when you use default package.
Typical Layout
The typical layout of Spring Boot application is shown in the image given below −
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]
The Application.java file should declare the main method along with
@SpringBootApplication. Observe the code given below for a better understanding −
package com.tutorialspoint.myproject;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {SpringApplication.run(Application.class,
args);}
}
Spring Boot - Runners
Application Runner and Command Line Runner interfaces lets you to execute the
code after the Spring Boot application is started. You can use these interfaces to
perform any actions immediately after the application has started. This chapter talks
about them in detail.
Application Runner
Application Runner is an interface used to execute the code after the Spring Boot
application started. The example given below shows how to implement the
Application Runner interface on the main class file.
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]
package com.tutorialspoint.demo;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication implements ApplicationRunner {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Override
public void run(ApplicationArguments arg0) throws Exception {
System.out.println("Hello World from Application Runner");
}
}
Now, if you observe the console window below Hello World from Application
Runner, the println statement is executed after the Tomcat started
package com.tutorialspoint.demo;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Override
public void run(String... arg0) throws Exception {
System.out.println("Hello world from Command Line Runner");
}
}
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]
Look at the console window below “Hello world from Command Line Runner” println statement
is executed after the Tomcat started.
If you are using Spring Boot Starters, Logback will provide a good support for
logging. Besides, Logback also provides a use of good support for Common Logging,
Util Logging, Log4J, and SLF4J.
Log Format
The default Spring Boot Log format is shown in the screenshot given below.
• Date and Time that gives the date and time of the log
• Log level shows INFO, ERROR or WARN
• Process ID
• The --- which is a separator
• Thread name is enclosed within the square brackets []
• Logger Name that shows the Source class name
• The Log message
1. Create a Spring Boot Project: Use Spring Initializr or an IDE to create a new Spring
Boot project with dependencies for Spring Web.
2. Define the Application Entry Point: This class starts the Spring application.
java
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]
Copy code
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
java
Copy code
package com.example.demo.model;
java
Copy code
package com.example.demo.service;
import org.springframework.stereotype.Service;
import com.example.demo.model.Greeting;
@Service
public class GreetingService {
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]
java
Copy code
package com.example.demo.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.model.Greeting;
import com.example.demo.service.GreetingService;
@RestController
public class GreetingController {
@Autowired
private GreetingService greetingService;
@GetMapping("/greeting")
public Greeting greeting(@RequestParam(value = "name", defaultValue = "World")
String name) {
return greetingService.getGreeting(1, name);
}
}
6. Run the Application: Use mvn spring-boot:run or run the main method in
DemoApplication.
Example Request
• URL: http://localhost:8080/greeting?name=John
• Response:
json
Copy code
{
"id": 1,
"content": "Hello, John!"
}
What is RestController
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]
RestController: RestController is used for making restful web services with the help of the
@RestController annotation. This annotation is used at the class level and allows the class to
handle the requests made by the client. Let’s understand @RestController annotation using an
example. The RestController allows to handle all REST APIs such
as GET, POST, Delete, PUT requests.
Controller:
Java
@RestController
// Class
public class Controller {
// Constructor
Controller()
{
a.add(1);
a.add(2);
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]
@GetMapping("/hello/{name}/{age}")
public void insert(@PathVariable("name") String name,
@PathVariable("age") int age)
{
// Annotation
@DeleteMapping("/hello/{id}")
// Method
public void deleteById(@PathVariable("id") int id)
{
a.remove(new Integer((id)));
print();
}
// Method
void print()
{
for (int elements : a) {
System.out.print(elements);
}
}
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]
Mapping Requests
This section discusses request mapping for annotated controllers.
@RequestMapping
We can use the @RequestMapping annotation to map requests to controllers methods. It has
various attributes to match by URL, HTTP method, request parameters, headers, and media
types. You can use it at the class level to express shared mappings or at the method level to
narrow down to a specific endpoint mapping.
There are also HTTP method specific shortcut variants of @RequestMapping:
• @GetMapping
• @PostMapping
• @PutMapping
• @DeleteMapping
• @PatchMapping
Example:
@RestController
@RequestMapping("/persons")
class PersonController {
@GetMapping("/{id}")
public Person getPerson(@PathVariable Long id) {
// ...
}
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public void add(@RequestBody Person person) {
// ...
}}
When you need to send data from a client (let's say, a browser) to your API, you send it as a
request body. A request body is data sent by the client to your API. A response body is the data
your API sends to the client. Your API almost always has to send a response body.
@RequestBody
@RequestBody is mainly used with CRUD Operations to read the request body.
Example:
@PostMapping("/addStudent")
public void AddStudent(@RequestBody Student student) {
// body}
DHANANJAYSHARMAOFFICIALS