1 of 35

Spring boot mvc

2 of 35

Spring Boot mvc

3 of 35

Client

(Browser)

WEB

server

dB

html

Client calls a program

server returns the Response

4 of 35

Request and Response

5 of 35

Spring MVC

  • Web application framework that takes advantage of design principles of Spring framework

  • Flexible and extensible via component’s

  • Simplified form handling through its parameter binding

  • Can do validation and error handling

6 of 35

MVC Architecture

  • Controller
    • Designed around a DispatcherServlet

  • Model
    • Can use any object as a command or form object.
    • Data binding is highly flexible. 

  • View
    • View resolution is extremely flexible.
    • View name resolution is configurable
    • Can use properties file to configure views

7 of 35

The requesting processing�workflow

8 of 35

@RequestMapping

  • Used to map URLs onto a class or a particular method.

  • Class-level annotation maps a specific request path or pattern to a controller

  • Method-level annotations are used to narrow the primary mapping
    • HTTP "GET"/"POST“ methods.

9 of 35

First Example

@Controller

@RequestMapping("/welcome")

public class WelcomeController {

@RequestMapping(value = "/greet",method = RequestMethod.GET)

@ResponseBody

public String message() {

return "Spring MVC";

}

}

http://localhost:8080/welcome/greet

10 of 35

Introduction to JSP Technology�

  • JSP pages, by virtue of the separate placement of the static and dynamic content, facilitates both Web developers and the Web designer to work independently.

  • Facilitates the segregation of the work profiles of a Web designer and a Web developer.

    • A Web designer can design and formulate the layout for a Web page by using HTML.

    • A Web developer, working independently, can use Java code and other JSP specific tags to code the business logic.

11 of 35

Jsp Scripting

  • Scriptlets
    • Java code placed inside JSP Page

<%

out.println("Hello From Jsp");

%>

12 of 35

Controller

@Controller

public class WelcomeController {

@RequestMapping("/welcome")

public String showLoginPage() {

return "welcome";

}

}

13 of 35

View Resolver

  • InternalResourceViewResolver 
    • Used to map the logical view names to view files

spring.mvc.view.prefix=/WEB-INF/pages/

spring.mvc.view.suffix=.jsp

14 of 35

Welcome.jsp

    • src/main/webapp/WEB-INF/pages

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

pageEncoding="ISO-8859-1"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="ISO-8859-1">

</head>

<body>

<h2>MVC Configured Successfully</h2>

</body>

</html>

15 of 35

Dependency Required

  • Update the pom.xml with following Dependencies
  • The Entries can be picked from the Effective Pom.

<dependency>

<groupId>org.apache.tomcat.embed</groupId>

<artifactId>tomcat-embed-jasper</artifactId>

</dependency>

<dependency>

<groupId>javax.servlet</groupId>

<artifactId>jstl</artifactId>

</dependency>

16 of 35

ModelAndView object

  • Encapsulates both model and view that is to be used to render model

  • Model is represented as a java.util.Map

  • Objects can be added to without name:

    • addObject(String, Object) – added with explicit name

    • addObject(Object) – added using name generation (Convention over Configuration)

  • View is represented by String or View object

17 of 35

Controller

@Controller

public class FirstController {

@RequestMapping("/first")

public ModelAndView execute()

{

String message = "Welcome to Spring!";

return new ModelAndView("Success", “msg",message);

}

}

18 of 35

@ModelAttribute

  • When Used as method parameter, maps a model attribute to the specific, annotated method parameter

  • The controller gets a reference to the object holding the data entered in the form.

  • When used at method level provides reference data for the model

  • The @ModelAttribute annotated methods are executed before the chosen @RequestMapping annotated handler method.

  • This helps in pre-populating the implicit model with specific attributes,

19 of 35

Model

  • A map object used to store attribute value pairs
  • It's created before invoking a handler method if the method has an argument type Model.
    • Stores attribute values to render dynamic views such as JSP.

  • addAttribute(String name, Object obj)
    • Used to map attribute names to object as attribute vales.

public String init(Model model) {

model.addAttribute("majHeading", "Jeevan Blood Bank");

return "index";

}

20 of 35

Model

@Data

@AllArgsConstructor

@NoArgsConstructor

@ToString

public class TripDetail {

private long tripId;

private String destination;

private double amount;

}

21 of 35

Controller

@Controller

public class TripController {

@Autowired

TripDetail detail;

@GetMapping("/")

public String init() {

return "index";

}

22 of 35

Controller

@GetMapping("/addTrip")

public String initForm(Model model) {

model.addAttribute("command",detail);

return "addTripDetails";

}

@PostMapping("/addTrip")

public String onSubmit(@ModelAttribute("data") TripDetail details) {

System.out.println(details);

return "success";

}

}

23 of 35

Using Spring's form tag library

  • Spring's form tag library gives the tags access to the command object and reference data of the controller

  • The form tag library comes bundled in spring-webmvc.jar.

  • The library descriptor is called spring-form.tld.

  • <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>

  • A Form tag puts the command object in the PageContext

24 of 35

View

<form:form action="/addTrip" method="post“ modelAttribute=“command”>

<form:form action="/addTrip" method="post">

<form:input path="tripId"/>

<form:input path="destination"/>

<form:input path="amount"/>

<input type="submit" value="Add">

</form:form>

From Spring 5.0

25 of 35

@RequestParam

  •  Use to bind request parameters to a method parameter in the controller.

@RequestMapping ("/find")

public String get ( @RequestParam ("custId") int id, Model model) {

Customer cust =dao.findByCustomerId(id);

model.addAttribute("foundCustomer",cust);

return "Display";

}

26 of 35

Spring Validation

  • JSR-303 Bean Validation API is used by Spring.

  • The standardized validation constraint declaration and metadata

  • Annotate domain model properties with declarative validation constraints and the runtime enforces them.

  • Can define own custom constraints.

  • To trigger validation of a @Controller input, Input arguments are annotated with @Valid

  • Using Hibernate Validator in the classpath, Spring will detect it and automatically support across all Controllers

27 of 35

Maven Dependency

<dependency>

<groupId>javax.validation</groupId>

<artifactId>validation-api</artifactId>

<version>2.0.0.Final</version>

</dependency>

<dependency>

<groupId>org.hibernate</groupId>

<artifactId>hibernate-validator</artifactId>

<version>5.4.0.Final</version>

</dependency>

28 of 35

Inbuilt Validation

  • @NotNull:
    • Field must not be null.
  • @NotBlank:
    • A string field must not be the empty string
    • Must have at least one character).
  • @Min and @Max:
    • Numerical field is only valid when it’s value is above or below a certain value.

29 of 35

Inbuilt Validation

  • @Pattern:
    • String field is only valid when it matches a certain regular expression.
    • @Pattern(regexp="[0-9]*")
  • @Email:
    • String field must be a valid email address.

  • @Past, @Future
    • Value must be a Date in the future or in the past

30 of 35

Inbuilt Validation

  • @Length(min=, max=)
    • Validates that the annotated character sequence is between min and max included.
  • @Range(min=, max=)
    • Checks whether the annotated value lies between (inclusive) the specified minimum and maximum
  • @DecimalMax
    • The field value must be a decimal value lower than or equal to the number in the value element

31 of 35

Model

public class BloodDonor {

private int id;

@Length(min = 3,max = 8)

private String name;

@DateTimeFormat(pattern = "yyyy-MM-dd")

private LocalDate dateOfBirth;

private String bloodGroup;

}

32 of 35

@Valid

  • @Valid
    • Spring does the validation
    • No need to create a validator object ourselves.
    • Need to tell Spring that we want to have a certain object validated.

  • Mostly Done on the POST and PUT requests
    • These methods take JSON payload within the request body.
    • Spring automatically maps the incoming JSON to a Java object.
    • To check if the incoming Java object meets requirements.

  • @Valid annotation in a controller checks and validates .

33 of 35

Binding Result

  • Spring’s object that holds the result of the validation and binding and contains errors that may have occurred.

  • The BindingResult must come right after the model object that is validated

    • Spring automatically picks up validation annotations
    • Spring then invokes the validator and puts any errors in the BindingResult
    • Adds the BindingResult to the view model.

34 of 35

Controller - @Valid annotation

@RequestMapping(“/donors")

public String initAddDonorForm(Model model) {

model.addAttribute("command",donor);

return "addDonor";

}

@PostMapping(path="/donors")

public String greetingSubmit(@Valid @ModelAttribute("command") BloodDonor donor, BindingResult result) {

if(result.hasErrors()) {

return "addDonor";

} else {

return "result";

}

}

35 of 35

Validation Input Jsp Page

<<form:form method="post" action=" donors" >

ID: <form:input path=“id" />

<form:errors path=“id" />

Name : <form:input path=“name" />

<form:errors path=“name" />

<input type="submit" value="Submit" />