Browse Source

not works

master
esoe 7 months ago
parent
commit
4d86752f5f
  1. 2
      client-service-teachers/src/main/java/ru/molokoin/clientserviceteachers/config/WebConfig.java
  2. 124
      client-service-teachers/src/main/java/ru/molokoin/clientserviceteachers/controllers/TeachersController.java
  3. 8
      client-service-teachers/src/main/resources/application.yaml
  4. 0
      client-service-teachers/src/main/resources/templates/index.html
  5. 59
      client-service-teachers/src/main/resources/templates/teachers.html
  6. 4
      resource-service-api/src/main/java/ru/molokoin/resourceserviceapi/controllers/TeacherController.java

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

@ -13,7 +13,7 @@ public class WebConfig { @@ -13,7 +13,7 @@ public class WebConfig {
WebClient webClient = WebClient.builder()
.baseUrl("http://resource-service-api:8181")
// .defaultCookie("cookie-name", "cookie-value")
.defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
// .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.build();
return webClient;
}

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

@ -16,10 +16,13 @@ import org.springframework.http.ResponseEntity; @@ -16,10 +16,13 @@ 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.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@ -40,6 +43,7 @@ import ru.molokoin.clientserviceteachers.entities.Teacher; @@ -40,6 +43,7 @@ import ru.molokoin.clientserviceteachers.entities.Teacher;
import ru.molokoin.clientserviceteachers.services.TeacherService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
@Controller
@ -48,32 +52,33 @@ public class TeachersController { @@ -48,32 +52,33 @@ public class TeachersController {
@Autowired
WebClient client;
@GetMapping("/teachers/resend")
public String infoResend(){
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_PLAIN);
HttpEntity<String> httpEntity = new HttpEntity<>(headers);
// @GetMapping("/teachers/resend")
// public String infoResend(){
// RestTemplate restTemplate = new RestTemplate();
// HttpHeaders headers = new HttpHeaders();
// headers.setContentType(MediaType.TEXT_PLAIN);
// HttpEntity<String> httpEntity = new HttpEntity<>(headers);
ResponseEntity<String> response =
restTemplate.exchange("http://resource-service-api:8181/teacher/list", HttpMethod.GET, httpEntity, String.class);
return response.getBody();
}
// ResponseEntity<String> response =
// restTemplate.exchange("http://resource-service-api:8181/teacher/list", HttpMethod.GET, httpEntity, String.class);
// return response.getBody();
// }
@GetMapping("/teachers")
public String listThy(Model model) throws JsonMappingException, JsonProcessingException{
Teacher teacher = new Teacher(
2, "first_name", "second_name", "last_name", "employee_id", "snils"
);
model.addAttribute("teacher", teacher);
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response =
restTemplate.exchange("http://resource-service-api:8181/teacher/list", HttpMethod.GET, null, String.class);
String json = response.getBody();
public String listThy(Model model, @ModelAttribute("teachers") @Validated List<Teacher> teachers) throws JsonMappingException, JsonProcessingException{
String json = client.method(HttpMethod.GET)
.uri("/teacher/list")
.retrieve()
.bodyToMono(String.class)
.block();
System.out.println("############################################################################");
System.out.println("############################################################################");
System.out.println("json :" + json);
ObjectMapper objectMapper = new ObjectMapper();
List<Teacher> teachers = objectMapper.readValue(json, new TypeReference<List<Teacher>>() {});
teachers = objectMapper.readValue(json, new TypeReference<List<Teacher>>() {});
model.addAttribute("teachers", teachers);
System.out.println("TEACHERS:" + teachers.toString());
return "teachers";
}
@ -105,7 +110,16 @@ public class TeachersController { @@ -105,7 +110,16 @@ public class TeachersController {
// return "teachers";
// }
// @PostMapping(path = "/teacher/add", consumes = {MediaType.APPLICATION_FORM_URLENCODED_VALUE})
/**
* Добавление сведений о преподавателе:
* - получение данных формы (в виде объекта teacher)
* - преобразование объекта teacher в json
* - отправка post запроса с данными json на сервис ресурсов
* - ожидание 1 секунду для уверенности, что запрос обработается сервером
* - направление пользователя на основную страницу
* @param teacher
* @return
*/
@PostMapping(
path = "/teacher/add",
consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE,
@ -116,33 +130,57 @@ public class TeachersController { @@ -116,33 +130,57 @@ public class TeachersController {
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());
}
.timeout(Duration.ofSeconds(1))
.block();
return "redirect:/teachers";
}
);
// @GetMapping(path = "/teacher/delete/{id}")
// public String deleteTeacherByGet(@PathVariable Long id){
// client.delete()
// .uri("/teacher/delete/" + id)
// .retrieve()
// // .toBodilessEntity()
// .bodyToMono(String.class)
// .timeout(Duration.ofSeconds(3)) // timeout
// .timeout(Duration.ofSeconds(1))
// // .onErrorResume(e -> Mono.empty())
// .block();
// return "redirect:/teachers";
// }
@DeleteMapping(path = "/teacher/delete/{id}")
public String deleteTeacher(@PathVariable Long id){
client.delete()
.uri("/teacher/delete/" + id)
.retrieve()
// .toBodilessEntity()
.bodyToMono(String.class)
.timeout(Duration.ofSeconds(1))
// .onErrorResume(e -> Mono.empty())
.block();
return "redirect:/teachers";
}
@PostMapping(
path = "/teacher/update/{id}",
consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE,
produces = {
MediaType.APPLICATION_JSON_VALUE
})
public String updateTeacher(@PathVariable Long id
, @ModelAttribute("teacher") @Validated Teacher teacher){
System.out.println(">>>>>>>>>>>>>> ####################### <<<<<<<<<<<<<<<<<<<<");
System.out.println(">>>>>>>>>>>>>> ####################### <<<<<<<<<<<<<<<<<<<<");
System.out.println(">>>>>>>>>>>>>>" + teacher.toString());
client.post()
.uri("/teacher/update/" + teacher.getId())
.body(Mono.just(teacher), Teacher.class)
.retrieve()
.toBodilessEntity()
.timeout(Duration.ofSeconds(1))
.block();
return "redirect:/teachers";
}
}

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

@ -6,4 +6,12 @@ spring: @@ -6,4 +6,12 @@ spring:
thymeleaf:
enabled: true
encoding: UTF-8
mode: LEGACYHTML5
# Разрешение на формирование скрытых запросов (DELETE)
mvc:
hiddenmethod:
filter:
enabled: true

0
client-service-teachers/src/main/resources/templates/index.html

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

@ -17,31 +17,27 @@ xmlns:th="http://www.thymeleaf.org"> @@ -17,31 +17,27 @@ xmlns:th="http://www.thymeleaf.org">
<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" />
<label>Фамилия: </label>
<input type="text" th:field="*{first_name}" placeholder="" />
</div>
<div>
<label>secondname</label>
<input type="text" th:field="*{second_name}" placeholder="string" />
<label>Имя: </label>
<input type="text" th:field="*{second_name}" placeholder="" />
</div>
<div>
<label>lastname</label>
<input type="text" th:field="*{last_name}" placeholder="string" />
<label>Отчество: </label>
<input type="text" th:field="*{last_name}" placeholder="" />
</div>
<div>
<label>Табельный номер</label>
<input type="text" th:field="*{employee_id}" placeholder="string" />
<input type="text" th:field="*{employee_id}" placeholder="" />
</div>
<div>
<label>СНИЛС</label>
<input type="text" th:field="*{snils}" placeholder="string" />
<input type="text" th:field="*{snils}" placeholder="" />
</div>
<input type="submit" value=обавить"/>
<input type="submit" value=ОБАВИТЬ"/>
</form>
<br>
@ -54,18 +50,35 @@ xmlns:th="http://www.thymeleaf.org"> @@ -54,18 +50,35 @@ xmlns:th="http://www.thymeleaf.org">
<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 th:each="teacher: ${teachers}" th:object="${teacher}">
<td>
<input type="text" th:field="${teacher.id}" placeholder="${teacher.id}"/>
</td>
<td>
<input type="text" th:field="${teacher.first_name}" placeholder="${teacher.first_name}"/>
</td>
<td>
<input type="text" th:field="${teacher.second_name}" placeholder="string"/>
</td>
<td>
<input type="text" th:field="${teacher.last_name}" placeholder="string"/>
</td>
<td>
<input type="text" th:field="${teacher.employee_id}" placeholder="string"/>
</td>
<td>
<input type="text" th:field="${teacher.snils}" placeholder="string"/>
</td>
<td>
<form th:action="@{teacher/update/{id}(id=${teacher.id})}" th:method="post">
<input type="submit" value="+"/>
</form>
<form th:action="@{teacher/delete/{id}(id=${teacher.id})}" th:method="delete">
<input type="submit" value="-"/>
</form>
</td>
</tr>
</table>
</div>

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

@ -52,7 +52,7 @@ public class TeacherController { @@ -52,7 +52,7 @@ public class TeacherController {
return new ResponseEntity<>(teacher, HttpStatus.CREATED);
}
@PutMapping(path = "/teacher/update/{id}",
@PostMapping(path = "/teacher/update/{id}",
consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> updateTeacher(@PathVariable Integer id, @RequestBody Teacher teacher) {
@ -70,7 +70,7 @@ public class TeacherController { @@ -70,7 +70,7 @@ public class TeacherController {
public ResponseEntity<String> deleteTecher(@PathVariable Long id){
Teacher t = repo.findTeacherById(id);
repo.delete(t);
return new ResponseEntity<>("Запись id#" + id + " удалена ... ", HttpStatus.NOT_FOUND);
return new ResponseEntity<>("Запись id#" + id + " удалена ... ", HttpStatus.OK);
}
}

Loading…
Cancel
Save