2021-03 spring-16-ajax added

This commit is contained in:
stvort
2021-05-26 01:41:58 +04:00
parent a60899a962
commit ae541da4d8
12 changed files with 335 additions and 0 deletions
+84
View File
@@ -0,0 +1,84 @@
<!DOCTYPE>
<html>
<head>
<title>Технологии JS для отправки запросов</title>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.21.1/axios.min.js"></script>
<script>
function getDataByXmlHttpRequest() {
const dataContainer = document.getElementById("dataContainer")
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = () => {
if(xhr.readyState === 4 && xhr.status === 200) {
// Вот здесь придёт ответ
const json = JSON.parse(xhr.responseText)
dataContainer.innerHTML = JSON.stringify(json, undefined, 4)
}
}
// Вот здесь запрос отправляется
xhr.open('GET', 'https://restcountries.eu/rest/v2/alpha/al')
xhr.send()
}
</script>
<script>
function getDataByJQuery() {
const dataContainer = document.getElementById("dataContainer")
$.ajax({
type: 'GET',
url: 'https://restcountries.eu/rest/v2/alpha/aw',
success: (json) => {
// Вот здесь пришёл ответ
dataContainer.innerHTML = JSON.stringify(json, undefined, 4)
}
})
}
</script>
<script>
function getDataByAxios() {
const dataContainer = document.getElementById("dataContainer")
axios.get('https://restcountries.eu/rest/v2/alpha/pl')
.then(json => dataContainer.innerHTML = JSON.stringify(json, undefined, 4))
}
</script>
<script>
function getDataByFetch() {
const dataContainer = document.getElementById("dataContainer")
fetch('https://restcountries.eu/rest/v2/alpha/co')
.then(response => response.json())
.then(json => dataContainer.innerHTML = JSON.stringify(json, undefined, 4))
}
</script>
</head>
<button onclick = "getDataByXmlHttpRequest()">Получить данные об Албании с помощью XMLHttpRequest</button><br/><br/>
<button onclick = "getDataByJQuery()">Получить данные об Арубе с помощью JQuery</button><br/><br/>
<button onclick = "getDataByAxios()">Получить данные о Польше с помощью Axios</button><br/><br/>
<button onclick = "getDataByFetch()">Получить данные о Колмбии с помощью Fetch</button><br/><br/>
<pre id = "dataContainer"></pre>
<body>
</body>
</html>
@@ -0,0 +1,72 @@
<?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>ru.otus</groupId>
<artifactId>spring-ajax-demo</artifactId>
<version>1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.5</version>
</parent>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<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>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,13 @@
package ru.otus.spring;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class);
}
}
@@ -0,0 +1,22 @@
package ru.otus.spring.domain;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "persons")
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(name = "name")
private String name;
}
@@ -0,0 +1,15 @@
package ru.otus.spring.page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class PersonPagesController {
@GetMapping("/")
public String listPage(Model model) {
model.addAttribute("keywords", "list users in Omsk, omsk, list users, list users free");
return "list";
}
}
@@ -0,0 +1,11 @@
package ru.otus.spring.repostory;
import org.springframework.data.repository.CrudRepository;
import ru.otus.spring.domain.Person;
import java.util.List;
public interface PersonRepository extends CrudRepository<Person, Long> {
List<Person> findAll();
}
@@ -0,0 +1,23 @@
package ru.otus.spring.rest;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import ru.otus.spring.repostory.PersonRepository;
import ru.otus.spring.rest.dto.PersonDto;
import java.util.List;
import java.util.stream.Collectors;
@RequiredArgsConstructor
@RestController
public class PersonController {
private final PersonRepository repository;
@GetMapping("/api/persons")
public List<PersonDto> getAllPersons() {
return repository.findAll().stream().map(PersonDto::toDto)
.collect(Collectors.toList());
}
}
@@ -0,0 +1,26 @@
/*
* Copyright 2016 Russian Post
*
* This source code is Russian Post Confidential Proprietary.
* This software is protected by copyright. All rights and titles are reserved.
* You shall not use, copy, distribute, modify, decompile, disassemble or reverse engineer the software.
* Otherwise this violation would be treated by law and would be subject to legal prosecution.
* Legal use of the software provides receipt of a license from the right name only.
*/
package ru.otus.spring.rest.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import ru.otus.spring.domain.Person;
@Data
@AllArgsConstructor
public class PersonDto {
private long id = -1;
private String name;
public static PersonDto toDto(Person person) {
return new PersonDto(person.getId(), person.getName());
}
}
@@ -0,0 +1,11 @@
spring:
datasource:
url: jdbc:h2:mem:testdb
initialization-mode: always
jpa:
generate-ddl: false
hibernate:
ddl-auto: none
show-sql: true
@@ -0,0 +1 @@
INSERT INTO persons (name) VALUES ('Pushkin'), ('Lermontov')
@@ -0,0 +1,8 @@
DROP TABLE IF EXISTS persons;
CREATE TABLE persons (
id BIGSERIAL,
name VARCHAR(250),
PRIMARY KEY (id)
);
@@ -0,0 +1,49 @@
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"/>
<meta name="keywords" th:content="${keywords}"/>
<title>List of all persons</title>
<style type="text/css">
body {
padding: 50px;
}
.persons, .persons td {
border: 1px solid lightgray;
padding: 5px;
}
</style>
<script src="/webjars/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<h1>Persons:</h1>
<table class="persons">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script>
$(function () {
$.get('/api/persons').done(function (persons) {
persons.forEach(function (person) {
$('tbody').append(`
<tr>
<td>${person.id}</td>
<td>${person.name}</td>
</tr>
`)
});
})
});
</script>
</body>
</html>