Session 12 Spring Framework Introduction 1 Reading & - - PDF document

session 12
SMART_READER_LITE
LIVE PREVIEW

Session 12 Spring Framework Introduction 1 Reading & - - PDF document

Session 11 Spring Framework Overview Session 12 Spring Framework Introduction 1 Reading & Reference Reading http://engineering.pivotal.io/post/must-know-spring-boot-annotations- controllers/


slide-1
SLIDE 1

Session 11 – Spring Framework Overview 11/3/2020 1 Robert Kelly, 2018-2020

1

Session 12

Spring Framework Introduction

Robert Kelly, 2018-2020

Reading & Reference

Reading

http://engineering.pivotal.io/post/must-know-spring-boot-annotations- controllers/ http://engineering.pivotal.io/post/spring-for-normal-people/ www.tutorialspoint.com/spring/spring_web_mvc_framework.htm https://springframework.guru/spring-requestmapping-annotation/

Reference

Spring home page

spring.io/

Spring 4.3 Reference Documentation

docs.spring.io/autorepo/docs/spring/4.3.0.RELEASE/spring-framework- reference/pdf/spring-framework-reference.pdf

2

slide-2
SLIDE 2

Session 11 – Spring Framework Overview 11/3/2020 2 Robert Kelly, 2018-2020

Robert Kelly, 2018-2020

Lecture Objectives

Understand the structure of the Spring controller Become familiar with Spring controller annotation

3 Robert Kelly, 2018-2020

Interesting Quote

Like many of my friends and fellow engineers, I have recently started working on some Spring projects, specifically using Spring

  • Boot. It has been several years since I have worked with Spring,

and some things were immediately apparent: I had no idea how to do things The Spring Way™. There is a ton of documentation. Almost all the documentation assumes you already know everything about Spring in order to understand it.

4

Source: Ian Fisher: Pivotal Engineering Post

slide-3
SLIDE 3

Session 11 – Spring Framework Overview 11/3/2020 3 Robert Kelly, 2018-2020

Robert Kelly, 2018-2020

Spring Overview

Open source, easy to use MVC Framework (tightly coupled to Servlet API) Integrates well with other tools Enables development of Java EE systems Initially developed in 2003 Currently well supported and expanding rapidly

5 Robert Kelly, 2018-2020

Spring Versions

Version 3.x – mapping are provided in xml files (similar to mappings found in web.xml and tld files Version 4.x (4.3 is final version in this series) – mappings use annotations Version 5.x

6

slide-4
SLIDE 4

Session 11 – Spring Framework Overview 11/3/2020 4 Robert Kelly, 2018-2020

Robert Kelly, 2018-2020

Inversion of Control

Design principle Custom written portions of a computer program receive the flow of control from a generic framework “Inversion” highlights the contrast with use of reusable libraries (e.g., APIs) that are called from a custom written control module Similar to event-driven programming

7 Robert Kelly, 2018-2020

Spring Architecture

Modular You can select which modules to use Modules

Data access (e.g., JDBC, object-relational mapping, JPA, etc.) Web Core Messaging Test More

8

slide-5
SLIDE 5

Session 11 – Spring Framework Overview 11/3/2020 5 Robert Kelly, 2018-2020

Robert Kelly, 2018-2020

Spring Boot

Pre-configured solution Requires you to provide exceptions rather than a complete configuration Integrates with Maven Features

Embedded application server No code generation No requirement for XML configuration files Spring initializer that will configure, download, and install your project files

9

https://start.spring.io/

Robert Kelly, 2018-2020

Maven

Build automation tool Collects all jars on classpath and builds a single runnable jar Apache Software Foundation XML file describes

How software is built Dependencies on external modules Build order Required plug-ins Directories

Projects configured using a Project Object Model (pom.xml)

10

<project> <modelVersion>4.0.0</modelVersion> <groupId>com.mycompany.app</groupId> <artifactId>my-app</artifactId> <version>1.0</version> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> </dependencies> </project>

Sample pom.xml file

slide-6
SLIDE 6

Session 11 – Spring Framework Overview 11/3/2020 6 Robert Kelly, 2018-2020

Robert Kelly, 2018-2020

Mapping Approach

Relationship between forms, servlets, views, and beans are specified in mapping files, not in the code Recall mapping done in web.xml and tld files Spring versions

Version 3.x – mapping are provided in xml files (similar to mappings found in web.xml and tld files Version 4.x – mappings use annotations

11 Robert Kelly, 2018-2020 12

Standard Servlet Control Flow

User agent Web Server Thymeleaf template RESTful Handler JSP

Your browser invokes a servlet (specified in URL), which then controls the server response

servlet servlet servlet

slide-7
SLIDE 7

Session 11 – Spring Framework Overview 11/3/2020 7 Robert Kelly, 2018-2020

Robert Kelly, 2018-2020 13

Servlet Mapping

User agent Web Server servlet HTML Page

Spring allows you to have a single controller receiving all requests

Thymeleaf template JSP

Spring allows you to specify a server method for each request

RESTful Handler

Robert Kelly, 2018-2020 14

Spring MVC

User agent Web Server Controller Other view

Think of the interaction as a user specified Controller object setting the rules for forwarding requests

Thymeleaf template JSP RESTful Handler Controller

slide-8
SLIDE 8

Session 11 – Spring Framework Overview 11/3/2020 8 Robert Kelly, 2018-2020

Robert Kelly, 2018-2020

Your First Spring Boot

Step-by-step instructions in We show the code, then look at how it works

15

dev.to/lechatthecat/how-to-use-spring-boot-java-web-framework-with-intellij-idea-202p

After we build the application, and enter localhost:8080 in the browser, this page appears

Robert Kelly, 2018-2020

Example

Intellij project Standard structure generated by Maven Contains

Java code Templates (e.g., Thymeleaf) Java tests Project Object Model

16

slide-9
SLIDE 9

Session 11 – Spring Framework Overview 11/3/2020 9 Robert Kelly, 2018-2020

Robert Kelly, 2018-2020

Example - Project Object Model …

<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.example</groupId> <artifactId>demo</artifactId> <version>1.0-SNAPSHOT</version> ...

17

An artifact is a file (e.g., JAR) that gets deployed to a Maven repository

Robert Kelly, 2018-2020

… Example - Project Object Model …

<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.2.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> </dependencies>

18

Maven automatically downloads dependencies pom.xml inherits from a super-pom

slide-10
SLIDE 10

Session 11 – Spring Framework Overview 11/3/2020 10 Robert Kelly, 2018-2020

Robert Kelly, 2018-2020

… Example - Project Object Model

<build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>

19 Robert Kelly, 2018-2020

Annotation Recap

Annotations can be defined to have elements Elements appear in parentheses following the annotation Elements are a collection of comma-separated, name-value pairs If the element name is missing, value is the default element name

20

@RequestMapping(method = RequestMethod.GET) @RequestMapping(“/welcome”)

Is the same as

@RequestMapping(value = “/welcome”)

slide-11
SLIDE 11

Session 11 – Spring Framework Overview 11/3/2020 11 Robert Kelly, 2018-2020

Robert Kelly, 2018-2020

Spring Boot Application

Runs a SpringApplication Specifies the main class @SpringBootApplication equivalent to

@Configuration, @EnableAutoConfiguration, and @ComponentScan

21

import

  • rg.springframework.boot.SpringApplication;

import

  • rg.springframework.boot.autoconfigure.Spri

ngBootApplication; @SpringBootApplication public class DemoApp { public static void main(String[] args) { SpringApplication.run(DemoApp.class, args); } }

Robert Kelly, 2018-2020

What Happens When Application Runs?

Configuration resolves Application server (e.g., Tomcat) runs Ready to accept requests to the server port (according to controller rules)

22

slide-12
SLIDE 12

Session 11 – Spring Framework Overview 11/3/2020 12 Robert Kelly, 2018-2020

Robert Kelly, 2018-2020

Example - Controller

Controller annotation (@Controller) indicates that the annotated class is a Web controller Controller class is auto- detected Typically use in combination with annotated handler methods based on RequestMapping annotation

23

package com.example.demo.controller; import org.springframework.stereotype.Controller; import

  • rg.springframework.web.bind.annotation.GetMapping;

@Controller public class HelloController { @GetMapping public String getHello() { return "hello"; } }

Shortcut for @RequestMapping with a GET parameter

Robert Kelly, 2018-2020

What Happens if We Change the Controller

Text (not html) is sent to browser

24

package com.example.demo.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; @RestController public class HelloController { @GetMapping public String getHello() { return "hello"; } }

slide-13
SLIDE 13

Session 11 – Spring Framework Overview 11/3/2020 13 Robert Kelly, 2018-2020

Robert Kelly, 2018-2020

Controller Types

Each controller contains annotation describing what type of controller it is @Controller

  • ften used to serve Web pages

Controller methods will return a String that indicates which template to render or which route to redirect to

@RestController

Serves text (JSON, XML, etc.) Controller methods return an object that will be serialized to the specified format

25 Robert Kelly, 2018-2020

Track Initializer

To build a Spring project in Intellij, you can use Spring Initializr Set Web dependencies

26

slide-14
SLIDE 14

Session 11 – Spring Framework Overview 11/3/2020 14 Robert Kelly, 2018-2020

Robert Kelly, 2018-2020 27

Spring MVC Control Flow

Handler Mapping DispatcherServlet

doGet / doPost HTTP Response

Controller View

Diagram from tutorialspoint.com

HandlerMapping is a Spring component set up by your controller annotation

Model Updates Model and returns View

View Resolver

Model

1 2 3 4

Controller methods

HandlerMapping, Controller, and ViewResolver are parts of WebApplicationContext

Robert Kelly, 2018-2020

Model

The Model object is a generalized version of the shared scopes (Session, ServletContext, etc.) Each contains name/value pairs Usually accessed as a ModelMap

28

slide-15
SLIDE 15

Session 11 – Spring Framework Overview 11/3/2020 15 Robert Kelly, 2018-2020

Robert Kelly, 2018-2020

ViewResolver

Allows you to render models in the browser Compatible with multiple view technologies Maps view names to actual views Spring contains multiple view resolvers, but you can add one of your own

29 Robert Kelly, 2018-2020

View

Html PDF XML Templates

JSP ThymeLeaf Velocity

30

slide-16
SLIDE 16

Session 11 – Spring Framework Overview 11/3/2020 16 Robert Kelly, 2018-2020

Robert Kelly, 2018-2020

Spring Controllers

Earlier, we reviewed a very simple example of a Controller One class, one method All request return a simple string (RestController) Today we look at variations on the simple controller

31

package com.example.demo.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; @RestController public class HelloController { @GetMapping public String getHello() { return "hello"; } }

Robert Kelly, 2018-2020

Request Mapping Basics

RequestDispatcher servlet routes HTTP requests to handler methods of controllers You specify the mapping of requests to handler methods using Spring annotation @RequestMapping – applied to classes and/or methods

32

The examples in this session use a RestController since it does not involve views

slide-17
SLIDE 17

Session 11 – Spring Framework Overview 11/3/2020 17 Robert Kelly, 2018-2020

Robert Kelly, 2018-2020

@RequestMapping With Multiple URIs

Reference states that you can provide an array of URI mappings Requires full specification of annotation Better to associate individual mappings with separate methods with common logic abstracted into a private method

33

@RestController @RequestMapping("/home") public class Cse336Controller { @RequestMapping( value={"", "view*", "page*, **/msg"}) String indexMultipleMapping(){ return "Hello from multiple mapping"; } }

Does not work correctly Notice the use of wild cards

Robert Kelly, 2018-2020

@RequestMapping with @RequestParam

@RequestParam used with @RequestMapping to bind a request parameter to the parameter of the handler method Note the differences in the two methods

34

@RequestMapping(value="/id") String getIdByValue( @RequestParam("id") String personId){ return "Get parameter of id = " + personId; } @RequestMapping(value="/personId") String getId(@RequestParam String personId) { System.out.println("ID is " + personId); return "Get parameter of personId = " + personId; }

Used when variable name matches html form component name Client sends a form dataset, which contains name/value pairs of html elements in an html form

slide-18
SLIDE 18

Session 11 – Spring Framework Overview 11/3/2020 18 Robert Kelly, 2018-2020

Robert Kelly, 2018-2020

@RequestMapping – Required Element

You can declare whether

  • r not a parameter is

required If required is false, you can specify a defaultValue as an annotation element

35

@RequestMapping("/name") String getName(@RequestParam(value="person", required= true) String personName) { return "Required name is " + personName; }

This Spring error message is returned when form parameter is not present

Robert Kelly, 2018-2020

@RequestMapping With HTTP Method

You can send different http requests with the same URI to different server methods. Use the RequestMethod enum Supported methods – GET, HEAD, POST, PUT, PATCH, and DELETE @GetMapping acts as a shortcut for @RequestMapping(method = RequestMethod.GET) Similar shortcuts for POST, PUT, DELETE, and PATCH

36

@RequestMapping( method = RequestMethod.POST)

slide-19
SLIDE 19

Session 11 – Spring Framework Overview 11/3/2020 19 Robert Kelly, 2018-2020

Robert Kelly, 2018-2020

Other Mappings

You can specify mappings with Producible and Consumable You can specify methods that respond to headers present in the request

37 Robert Kelly, 2018-2020

Have You Satisfied the Lecture Objectives?

Understand the structure of the Spring controller Become familiar with Spring controller annotation

38