Browse Source

post teacher

master
esoe 7 months ago
parent
commit
102e2968d4
  1. 4
      client-service-teachers/pom.xml
  2. 20
      client-service-teachers/src/main/java/ru/molokoin/clientserviceteachers/config/WebConfig.java
  3. 88
      client-service-teachers/src/main/java/ru/molokoin/clientserviceteachers/controllers/TeachersController.java
  4. 22
      client-service-teachers/src/main/java/ru/molokoin/clientserviceteachers/services/TeacherService.java
  5. 4
      client-service-teachers/src/main/resources/application.yaml
  6. 62
      client-service-teachers/src/main/resources/templates/teachers.html
  7. 2
      docker-compose.yaml
  8. 11
      resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/controllers/TeacherController.java

4
client-service-teachers/pom.xml

@ -17,6 +17,10 @@ @@ -17,6 +17,10 @@
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>

20
client-service-teachers/src/main/java/ru/molokoin/clientserviceteachers/config/WebConfig.java

@ -0,0 +1,20 @@ @@ -0,0 +1,20 @@
package ru.molokoin.clientserviceteachers.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.client.WebClient;
@Configuration
public class WebConfig {
@Bean
public WebClient webClient() {
WebClient webClient = WebClient.builder()
.baseUrl("http://resource-service-api:8181")
// .defaultCookie("cookie-name", "cookie-value")
.defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.build();
return webClient;
}
}

88
client-service-teachers/src/main/java/ru/molokoin/clientserviceteachers/controllers/TeachersController.java

@ -1,22 +1,33 @@ @@ -1,22 +1,33 @@
package ru.molokoin.clientserviceteachers.controllers;
import java.net.URI;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.ClientRequest;
import org.springframework.web.reactive.function.client.ClientResponse;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.WebClientResponseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
@ -24,11 +35,19 @@ import com.fasterxml.jackson.databind.JsonMappingException; @@ -24,11 +35,19 @@ import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import reactor.core.publisher.Mono;
import ru.molokoin.clientserviceteachers.entities.Teacher;
import ru.molokoin.clientserviceteachers.services.TeacherService;
import org.springframework.web.bind.annotation.PostMapping;
@Controller
@RequestMapping(path = "/")
public class TeachersController {
@Autowired
WebClient client;
@GetMapping("/teachers/resend")
public String infoResend(){
RestTemplate restTemplate = new RestTemplate();
@ -57,4 +76,73 @@ public class TeachersController { @@ -57,4 +76,73 @@ public class TeachersController {
model.addAttribute("teachers", teachers);
return "teachers";
}
/**
* сохранение записи о новом преподавателе:
* - подготовка сущности записи
* - преобразование записи в json
* - отправка post запроса на сервис-ресурсов
*
* @param entity
* @return
* @throws JsonProcessingException
*/
// @PostMapping(path = "/teacher/create",
// consumes = {MediaType.APPLICATION_FORM_URLENCODED_VALUE})
// public String postMethodName(@RequestBody Teacher teacher) throws JsonProcessingException {
// String url = "http://resource-service-api:8181/teacher/create";
// // model.addAttribute("teacher", teacher);
// RestTemplate restTemplate = new RestTemplate();
// // HttpHeaders headers = new HttpHeaders();
// // headers.setContentType(MediaType.APPLICATION_JSON);
// ObjectMapper objectMapper = new ObjectMapper();
// String json = objectMapper.writeValueAsString(teacher);
// System.out.println("СООБЩЕНИЕ ИЗ СЕРВИСА-КЛИЕНТОВ:");
// System.out.println(json);
// // ResponseEntity<String> response =
// // restTemplate.postForEntity(url, teacher, Teacher.class);
// restTemplate.postForEntity(url, json, String.class);
// return "teachers";
// }
// @PostMapping(path = "/teacher/add", consumes = {MediaType.APPLICATION_FORM_URLENCODED_VALUE})
@PostMapping(
path = "/teacher/add",
consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE,
produces = {
MediaType.APPLICATION_JSON_VALUE
})
public String postTeacher(@ModelAttribute("teacher") @Validated Teacher teacher){
client.post()
.uri("/teacher/create")
.body(Mono.just(teacher), Teacher.class)
// .bodyValue(BodyInserters.fromValue(teacher))
.retrieve()
.toBodilessEntity()
.subscribe(
responseEntity -> {
// Handle success response here
HttpStatusCode status = responseEntity.getStatusCode();
URI location = responseEntity.getHeaders().getLocation();
// handle response as necessary
},
error -> {
// Handle the error here
if (error instanceof WebClientResponseException) {
WebClientResponseException ex = (WebClientResponseException) error;
HttpStatusCode status = ex.getStatusCode();
System.out.println("!!!Error Status Code: " + status.value());
//...
} else {
// Handle other types of errors
System.err.println("!!!An unexpected error occurred: " + error.getMessage());
}
}
);
// .bodyToMono(String.class)
// .timeout(Duration.ofSeconds(3)) // timeout
// .block();
return "redirect:/teachers";
}
}

22
client-service-teachers/src/main/java/ru/molokoin/clientserviceteachers/services/TeacherService.java

@ -0,0 +1,22 @@ @@ -0,0 +1,22 @@
package ru.molokoin.clientserviceteachers.services;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import lombok.AllArgsConstructor;
import reactor.core.publisher.Mono;
import ru.molokoin.clientserviceteachers.entities.Teacher;
@Service
@AllArgsConstructor
public class TeacherService {
private final WebClient webClient;
public Mono<Teacher> getTeacherByIdAsync(final String id){
return webClient
.get()
.uri(String.join("", "/teacher/", id))
.retrieve()
.bodyToMono(Teacher.class);
}
}

4
client-service-teachers/src/main/resources/application.yaml

@ -3,3 +3,7 @@ server: @@ -3,3 +3,7 @@ server:
spring:
application:
name: client-service-teachers
thymeleaf:
enabled: true
encoding: UTF-8

62
client-service-teachers/src/main/resources/templates/teachers.html

@ -8,17 +8,67 @@ xmlns:th="http://www.thymeleaf.org"> @@ -8,17 +8,67 @@ xmlns:th="http://www.thymeleaf.org">
<script type="module" src="https://cdn.jsdelivr.net/gh/zerodevx/zero-md@1/src/zero-md.min.js"></script>
</head>
<body>
<header>
menu : auth
</header>
<main>
<div class="main-wraper">
<zero-md th:src="@{/teachers.md}"></zero-md>
<br><br>
<!-- <span th:text="${teacher.id}"></span>
<br><br>
<span th:text="${teacher.first_name}"></span> -->
<br>
<h2>Добавление преподавателя:</h2>
<form th:action="@{/teacher/add}" method="post" th:object="${teacher}">
<!-- <div>
<label>id</label>
<input type="text" th:field="*{teacher.id}" placeholder="long" />
</div> -->
<div>
<label>firstname</label>
<input type="text" th:field="*{first_name}" placeholder="string" />
</div>
<div>
<label>secondname</label>
<input type="text" th:field="*{second_name}" placeholder="string" />
</div>
<div>
<label>lastname</label>
<input type="text" th:field="*{last_name}" placeholder="string" />
</div>
<div>
<label>Табельный номер</label>
<input type="text" th:field="*{employee_id}" placeholder="string" />
</div>
<div>
<label>СНИЛС</label>
<input type="text" th:field="*{snils}" placeholder="string" />
</div>
<input type="submit" value="Добавить"/>
</form>
<tbody>
<br>
<h2>Перечень преподавателей:</h2>
<table>
<tr>
<th>id</th>
<th>firstname</th>
<th>secondname</th>
<th>lastname</th>
<th>Табельный номер</th>
<th>СНИЛС</th>
<!-- <th>save</th> -->
<th>delete</th>
</tr>
<tr th:each="teacher: ${teachers}">
<td th:text="${teacher.id}" />
<td th:text="${teacher.first_name}" />
<td th:text="${teacher.second_name}"></td>
<td th:text="${teacher.last_name}"></td>
<td th:text="${teacher.employee_id}"></td>
<td th:text="${teacher.snils}"></td>
<!-- <td>+</td> -->
<td>-</td>
</tr>
</tbody>
</table>
</div>
</main>
</body>
</html>

2
docker-compose.yaml

@ -1,4 +1,4 @@ @@ -1,4 +1,4 @@
version: "3"
version: "3.7"
services:
client-service-teachers:
build: client-service-teachers/

11
resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/controllers/TeacherController.java

@ -5,6 +5,7 @@ import java.util.Map; @@ -5,6 +5,7 @@ import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
@ -23,7 +24,7 @@ import org.springframework.web.bind.annotation.RequestBody; @@ -23,7 +24,7 @@ import org.springframework.web.bind.annotation.RequestBody;
* - запросы к страницам по id, которых нет в базе
*/
@RestController
@RequestMapping(path = "/")
@RequestMapping(path = "/", consumes = {"*/*"})
public class TeacherController {
@Autowired
private TeachersRepositoryFace repo;
@ -43,13 +44,17 @@ public class TeacherController { @@ -43,13 +44,17 @@ public class TeacherController {
* @param teacher
* @return
*/
@PostMapping("/teacher/save")
@PostMapping(path = "/teacher/create",
consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> saveTeacher(@RequestBody Teacher teacher) {
repo.save(teacher);
return new ResponseEntity<>(teacher, HttpStatus.CREATED);
}
@PutMapping("/teacher/update/{id}")
@PutMapping(path = "/teacher/update/{id}",
consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> updateTeacher(@PathVariable Integer id, @RequestBody Teacher teacher) {
Teacher t = repo.findTeacherById(id);
t.setFirst_name(teacher.getFirst_name());

Loading…
Cancel
Save