0% found this document useful (0 votes)
13 views

Chapter III SpringBoot - Part 6 - Control

Controllers in Spring Boot handle HTTP requests and return responses. They are defined using @Controller and @RestController annotations. Controller methods use annotations like @RequestMapping, @GetMapping, @PostMapping to map HTTP request types to methods. Path variables and request parameters allow extracting dynamic values from the URL and request. The @ModelAttribute annotation binds form data to Java objects. Validation uses the @Valid annotation to validate input objects. Redirects instruct the browser to request a new URL, while forwards pass control internally without client awareness.

Uploaded by

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

Chapter III SpringBoot - Part 6 - Control

Controllers in Spring Boot handle HTTP requests and return responses. They are defined using @Controller and @RestController annotations. Controller methods use annotations like @RequestMapping, @GetMapping, @PostMapping to map HTTP request types to methods. Path variables and request parameters allow extracting dynamic values from the URL and request. The @ModelAttribute annotation binds form data to Java objects. Validation uses the @Valid annotation to validate input objects. Redirects instruct the browser to request a new URL, while forwards pass control internally without client awareness.

Uploaded by

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

1

CONTROL
SPRING BOOT / CONTROLLER

§ In Spring Boot, a controller is a Java class that

§ Handles incoming HTTP requests,

§ Invokes the corresponding service methods,

§ Returns the appropriate HTTP response.

§ Controllers can be defined in a Spring Boot using two annotations:

§ @Controller

§ @RestController

2
SPRING BOOT / CONTROLLER

§ The @Controller annotation is used to declare that this class is a Spring MVC controller.

§ The @RequestMapping annotation is used at the class level to specify the base URL path
("/mycontroller") for all the handler methods in this controller.

§ Controller methods will be responsible for processing different types of requests (GET, POST,
etc.) 3
SPRING BOOT / CONTROLLER METHODS

§ In a Spring Boot application, controller methods are responsible for handling incoming
HTTP requests.

§ A method in the controller handles one HTTP request.

§ The type of request that a method handles is determined by the @RequestMapping


annotation on the method or its specialized variants like @GetMapping,
@PostMapping, @DeleteMapping, @PutMapping.

§ The annotation specifies also the URL path that the method is responsible for.

4
SPRING BOOT / CONTROLLER METHODS

5
SPRING BOOT / PATH VARIABLE
§ Path Variable: is a placeholder in the URL pattern of a web request that is used to extract

values dynamically from the request URI.

§ In Spring Boot, you can use the @PathVariable annotation to capture these values and
use them as method parameters in your controller methods.

§ Placeholder in URL: Path variables are often denoted by curly braces {} within the URL
pattern. For example, in the URL "/getUser/{id}", {id} is a path variable.

§ Dynamic Values: Path variables allow you to capture dynamic values from the URL. For

example, in the URL “…../getUser/123 ”, 123 can be a dynamic value for the “ id ” path
variable.
6
SPRING BOOT / PATH VARIABLE

§ The @PathVariable annotation on the id parameter of the getUser method indicates


that the value extracted from the ”id" path variable in the URL should be assigned to
this method parameter.

§ When a request is made to "/getUser/123", the value "123" will be extracted from the
URL and passed as the id parameter to the getUser method. 7
SPRING BOOT / REQUEST PARAMETER

§ In Spring Boot, a request parameter is a piece of data sent to the server as part of an
HTTP request.

§ Request parameters are typically used to pass information from the client (browser) to
the server (for example from a form).

§ In Spring Boot, the @RequestParam annotation is used to extract and bind request
parameters to method parameters in your controller methods.

8
SPRING BOOT / REQUEST PARAMETER

§ The @RequestParam String firstName annotation indicates that the value of the
"firstName" request parameter will be extracted from the request URL and bound to the
firstName method parameter.

9
SPRING BOOT / REQUEST PARAMETER MAP

§ The @RequestParam Map annotation in Spring MVC is used to bind all request
parameters to a Map<String, String> parameter in a controller method.

§ This can be useful when you want to handle a variable number of request
parameters without explicitly declaring each one as a method parameter.

10
SPRING BOOT / REQUEST PARAMETER

§ @RequestParam Map<String, String> searchParams: This parameter is annotated with


@RequestParam, but since it is of type Map<String, String>, it collects all request
parameters into a Map.

§ This map is named searchParams and contains the key-value pairs of the request
parameters.
11
SPRING BOOT / REQUEST BODY

§ The @RequestBody annotation in Spring MVC is used to indicate that a method


parameter should be bound to the body of the HTTP request.

§ This annotation is typically used in conjunction with the @PostMapping or


@RequestMapping annotations, where the HTTP request method is POST or another
method that can include a request body.

12
SPRING BOOT / REQUEST BODY

§ @RequestBody User user is used to indicate that the user parameter should be
populated with the data from the request body.

§ The User class represents the structure of the data you expect in the request body.
13
SPRING BOOT / MODEL INTERFACE

§ In a Spring boot controller, the Model interface is used to pass data from the controller to
the view.

§ It allows you to add attributes, and these attributes can be accessed by the view template
to render dynamic content.

§ The Model object acts as a container for data that needs to be displayed on the client side.

§ The model object can store data with primitive types (int, double, float, etc), String,
Objects, collections (List, Set, Map, etc), Array, etc.

§ Data is added to the Model object by invoking the addAttribute method.


14
SPRING BOOT / MODEL INTERFACE

§ Model model: This parameter is used to add attributes to the model. The Model is a
container for data that will be passed to the view.

§ model.addAttribute("myUser", myUser): The retrieved User object (myUser) is added as


an attribute to the model. The attribute is named "myUser," and its value is the User
object. This attribute can be accessed in the view.
15
SPRING BOOT / MODEL INTERFACE

16
SPRING BOOT / MODEL ATTRIBUTE

§ In Spring Boot, @ModelAttribute is used to bind form data to a Java object.

§ This annotation can be applied to a method parameter or a method in a controller class,

§ It indicates that the parameter or the return value of the method should be used as a
model attribute.

17
SPRING BOOT / MODEL ATTRIBUTE

§ Inside the method showAddUserForm, a new User object is added to the model
with the attribute name "user".

§ This is done to bind the form fields to this User object when the form is submitted.

§ The method addUser takes a User object as a parameter, annotated with


@ModelAttribute.

§ The User object is automatically populated with the form data submitted from the

view.

18
SPRING BOOT / VALIDATION
§ In Spring MVC, the @Valid annotation is used for input validation.

§ This annotation is commonly applied to method parameters in controllers to indicate


that the input should be validated before further processing.

§ @Valid annotation is placed on a method parameter in your controller method that


receives input data.

§ The parameter type should be a Java bean or a DTO (Data Transfer Object) that
contains validation constraints using annotations from the javax.validation.constraints
package.

19
SPRING BOOT / VALIDATION

§ The @Valid annotation on the User parameter triggers validation on the User object based on the

validation constraints specified in the User class.

§ If there are validation errors, they will be captured in the BindingResult object.

§ The method checks if there are any validation errors by calling bindingResult.hasErrors().

§ If validation errors exist, the control flow returns to the "addUserForm" view, where a message error is

displayed. 20
SPRING BOOT / REDIRECTS AND FORWARDING

§ In Spring Boot, redirects and forwards are mechanisms used for

§ Controlling navigation.

§ Handling the flow of a web application.

§ These mechanisms are often employed to:

§ Direct the user to a different URL.

§ Pass control to another controller method.

21
SPRING BOOT / REDIRECT
§ A redirect instructs the browser to make a new request to a different URL.

§ This is typically used when you want to send the user to another page after processing

some data.

§ In Spring Boot, the “redirect” prefix is used in the return statement to specify the URL
to redirect to.

22
SPRING BOOT / REDIRECT

23
SPRING BOOT / FORWARD

§A forward is an internal operation that forwards the control to another


controller method without the client being aware of it.

§ It is often used to reuse the processing logic of one controller method in


another.

§ In Spring Boot, the forward prefix is used in the return statement to specify the
path to forward to.

24
SPRING BOOT / FORWARD

25
SPRING BOOT / REST CONTROLLER
§ In Spring Boot, a @RestController is a specialized version of the @Controller annotation
that is used to define RESTful web services.

§ It's a convenient way to create web applications that follow the principles of
Representational State Transfer (REST).

§ The primary purpose of a @RestController is to handle HTTP requests and produce HTTP
responses for RESTful services.

§ It's commonly used to build APIs that can be consumed by clients such as web browsers,
mobile applications, or other servers.
26
SPRING BOOT / REST CONTROLLER
§ The @RestController annotation is a composed annotation that includes both
@Controller and @ResponseBody.

§ The @Controller part indicates that the class is a Spring MVC controller, and
@ResponseBody indicates that the return value of methods should be serialized directly
to the response body.

§ By default, the response content type for methods in a @RestController is JSON. This
means that the return values of the methods are automatically serialized to JSON format
and sent as the response body.

27
SPRING BOOT / REST CONTROLLER
§ Supports HTTP Methods Mapping: Like @Controller, @RestController supports mapping
methods to specific HTTP methods using annotations such as @GetMapping,
@PostMapping, @PutMapping, @DeleteMapping, etc

28
SPRING BOOT / REST CONTROLLER
Characteristic @Controller (MVCController) @RestController
Primarily used for building Designed for building RESTful web
Purpose traditional web applications with services that return data in a
HTML views. format like JSON or XML.
Annotation @Controller @RestController
Returns the actual data (e.g.,
Typically returns a logical view objects, JSON, XML) and relies on
Response Handling name which is resolved by a the HTTP message converter to
view resolver. convert the data to the
appropriate format.
Uses view resolvers to map
Does not involve view resolution;
logical view names to actual
View Resolution the return value is directly
view implementations (HTML,
serialized to the response body.
JSP, Thymeleaf, etc.). 29

You might also like