Giter VIP home page Giter VIP logo

springinaction6's Introduction

Spring In Action 6th Edition

Spring Frame Class Work by Craig Walls

"Spring offers a container, reffered to as the Spring Application context. It creates and manages application components."

  • Data persistance options
  • Microserve support
  • Reactive programming model
  • Runtime monitoring
  • Security framework

MVC (Model-View-Controller) is a pattern in software design commonly used to implement user interfaces, data, and controlling logic. It emphasizes a separation between the software's business logic and display. This "separation of concerns" provides for a better division of labor and improved maintenance. Some other design patterns are based on MVC, such as MVVM (Model-View-Viewmodel), MVP (Model-View-Presenter), and MVW (Model-View-Whatever).

  1. Model: Manages data and business logic.
  2. View: Handles layout and display.
  3. Controller: Routes commands to the model and view parts.

Data-3

Annotation note reference

@Configuration

This annotation is used on classes which define beans. @Configuration is an analog for XML configuration file – it is configuration using Java class. Java class annotated with @Configuration is a configuration by itself and will have methods to instantiate and configure the dependencies.

@Bean

This annotation is used at the method level. @Bean annotation works with @Configuration to create Spring beans. As mentioned earlier, @Configuration will have methods to instantiate and configure dependencies. Such methods will be annotated with @Bean. The method annotated with this annotation works as bean ID and it creates and returns the actual bean.

Spring Initializer: init

How to make a New Project:

grsb

Create New Project:

new

Click Next and wizard takes you to setting up dependencies: dev

Then search for the missing dependencies eg. Spring Web and add it:

search

How the project looks once you click Finish and it has finished loading:

project

More about the files:

files

Open the Taco Test File to view this code:

taco

Running the Maven Test File:

runtest

run

Create a new class in the tacos package:

createclass

Adding the code to the home controller class:

homecontroller

Annotation note reference

@Component

This annotation is used on classes to indicate a Spring component. The @Component annotation marks the Java class as a bean or say component so that the component-scanning mechanism of Spring can add into the application context.

@Service

This annotation is used on a class. The @Service marks a Java class that performs some service, such as execute business logic, perform calculations and call external APIs. This annotation is a specialized form of the @Component annotation intended to be used in the service layer.

@Repository

This annotation is used on Java classes which directly access the database. The @Repository annotation works as marker for any class that fulfills the role of repository or Data Access Object.

This annotation has a automatic translation feature. For example, when an exception occurs in the @Repository there is a handler for that exception and there is no need to add a try catch block.

@GetMapping

This annotation is used for mapping HTTP GET requests onto specific handler methods. @GetMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.GET)

Create a new HTML file in the template folder under src: html

Add your taco image and images folder to the static folder:

images

Create a Test File:

test class

Run the test in IDE: $ mvnw test

Run Spring Boot App:

runspringbootapp

Open your borswer and search localhost:8080

localhost8080

How do I install and use the browser extensions? Download & open to install:

  • Safari extension 2.1.0 — note: due to Safari API limitations, browser extension does not work with file: URLs; if you’re working with local files via file: URL, please use Chrome or insert the SCRIPT snippet.

  • Chrome extension on the Chrome Web Store — if you want to use it with local files, be sure to enable “Allow access to file URLs” checkbox in Tools > Extensions > LiveReload after installation.

  • Firefox extension 2.1.0 from addons.mozilla.org.

Insight into the data your application is working with: http://localhost:8080/h2-console

Spring Dependencies:

The Core Spring Framework

Spring Boot

Spring Data

spring-security-core

<properties> <spring-security.version>5.3.4.RELEASE</spring-security.version> <spring.version>5.2.8.RELEASE</spring.version> </properties> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-core</artifactId> <version>${spring-security.version}</version> </dependency>

spring-security-web

<dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> <version>${spring-security.version}</version> </dependency>

spring-security-config

<dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-config</artifactId> <version>${spring-security.version}</version> </dependency>

Spring Integration and Spring Batch

Spring CLoud

Spring Native

Instead of starting from scratch, import chapter 1 code as a starter for chapter 2:

imports

Please note that doing it this way will sow down your machince and will take a while to load. Rather start a new file or build on the pervious version.

Lombok

Lombok tutorial

Add -> Spring -> Add Starters -> SELECT POM file

springlombokstarter clickpom

Watch this tuotorial if you aren't sure how to save your jar file that you have downloaded from the Project Lombok web page.

jar install java waiting

Simple Logging Facade for Java SLF4J

Serves as a simple facade or abstraction for various logging frameworks (e.g. java.util.logging, logback, log4j) allowing the end user to plug in the desired logging framework at deployment time. READ THE MANUAL

concrete-bindings

summary

Designing the view

  • JavaServer Pages (JSP)
  • Thymeleaf

<p th:text="${message}">placeholder message</p>:Thymeleaf templates are just HTML with some additional element attributes that guide a template in rendering request data.

${}: operator tells it to use the value of a request attribute ("message", in this case).

th:each:iterates over a collection of elements, rendering the HTML once for each item in the collection.

  • FreeMarker
  • Mustache
  • Groovy-based templates

localhost:8080/design in your browser to view

design

The Taco OrderForm.html File

page2

Spring supports the JavaBean Validation API JSR 303 java

Adding a Valedation dependency to your pom.xml file:

Right click on your pom file and say Spring -> Add Starters Then you will see this pop up validation step

Select pom only:

pom

This is the new code you will have in your file:

added

The Luhn Algorithm for Credit Card Validation

@CreditCardNumber ccNumber property Luhn algorithm check

How to calculate a Luhn checksum:

  1. From the rightmost digit (the check digit), move left and double the value of every second digit; if doubled number is greater than 9 (e.g., 7 × > 2 = 14), then subtract 9 from the product (e.g., 14: 14 - 9 = 5).
  2. Sum of all the digits in the newly calculated number.
  3. Multiply the sum by 9, the Luhn check digit is the rightmost digit of the result (e.g, the result modulo 10).

In the following example, we use a sample credit card number "7992739871", with an unknown Luhn check digit at the end, displayed as 7992739871x: luhn

The sum of all the digits in the third row above is 67+x.

We still need to calculate the check digit, X. The check digit can be obtained by computing the sum of the non-check digits then computing 9 times that value modulo 10. For our example, the equation is 67 × 9 mod 10. Broken down in more detail:

  1. Compute the sum of the non-check digits (67).
  2. Multiply by 9 (603).
  3. The units digit (3) is the check digit. Thus, x=3.

Domain Driven Design (DDD)

Core concepts of DDD: Aggregates and aggregate roots - a design approach that promotes the idea that the structure and language of software code should match the business domain.

Data-3

Read for more info on the topic Domain-Driven Design: Tackling Complexity in the Heart of Software

Selenium jar

Download your selenium jar file then follow these steps..

in your menu select build path

seleniumbuildpath

Go into your library and choose add extrnal jar and select your jar file.

library_addExternalJar

chooseyourseleniumjar

Watch this video if you are struggling with your selenium dependency: Tutorial

What the new login form looks like after Chapter 5 workinglogin

Configuration

Fine-tuning configuration

  • Bean wiring: Configuration that declares application components to be created as beans in the Spring application context and how they should be injected into each other
  • Property injection: Configuration that sets values on beans in the Spring application context Data-4

YAML

Known as ain’t markup language OR yet another markup language More Info Here

  • Features that come from Perl, C, XML, HTML, and other programming languages. YAML is also a superset of JSON, so JSON files are valid in YAML.
  • Python-style indentation to indicate nesting.
  • Tab characters are not allowed, so whitespaces are used instead. There are no usual format symbols, such as braces, square brackets, closing tags, or quotation marks.
  • YAML files use a .yml or .yaml extension.
  • The structure of a YAML file is a map or a list.
  • Contains scalars, which are arbitrary data (encoded in Unicode) that can be used as values such as strings, integers, dates, numbers, or booleans.

More YAML examples and usage: 1 2 3

REST services

HTTPie is making APIs simple and intuitive for those building the tools of our time. httpie

Testing the api api

CommandLine test in Terminal

commandlinetest

RESTful Controllers:

05fig01 05fig02_alt

Read more

restful

Testing the Taco Application:

localhost:8080/tacos/apis/4 The 404 page not found code HTTPanswer

localhost:8080/tacos/apis/3 3

localhost:8080/ingredients

ingredients

$ curl http://localhost:8080/ingredients/FLTO

tortilla

Adding

spring:
   data:
     rest:
       base-path: /data-api

to the application.yml file

$ curl http://localhost:8080/data-api/tacos $ curl http://localhost:8080/data-api/tacoes testing

localhost:8080/data-api

api

Paging and Sorting: requesting the first page of tacos where the page size is 5, you can issue the following GET request (using curl):

curl "localhost:8080/data-api/tacos?size=5"

pagingsorting

Links working:

Firefox Browser

firefox

Chrome Browser - Add the JSON viewer extension

localhost

JSONview Download

Hypermedia as the Engine of Application State

Consuming REST services

A Spring application can consume a REST API with the following:

  • RestTemplate—A straightforward, synchronous REST client provided by the core Spring Framework.
  • Traverson—A wrapper around Spring’s RestTemplate, provided by Spring HATEOAS, to enable a hyperlink-aware, synchronous REST client. Inspired from a JavaScript library of the same name.
  • WebClient—A reactive, asynchronous REST client.

table

LAST UPDATE: May 2022

springinaction6's People

Contributors

rominalodolo avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.