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 {
WebClient webClient = WebClient.builder() WebClient webClient = WebClient.builder()
.baseUrl("http://resource-service-api:8181") .baseUrl("http://resource-service-api:8181")
// .defaultCookie("cookie-name", "cookie-value") // .defaultCookie("cookie-name", "cookie-value")
.defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) // .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.build(); .build();
return webClient; return webClient;
} }

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

@ -16,10 +16,13 @@ import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.ui.Model; import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated; 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.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute; 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.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping; 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.ResponseBody;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate; import org.springframework.web.client.RestTemplate;
@ -40,6 +43,7 @@ import ru.molokoin.clientserviceteachers.entities.Teacher;
import ru.molokoin.clientserviceteachers.services.TeacherService; import ru.molokoin.clientserviceteachers.services.TeacherService;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
@Controller @Controller
@ -48,32 +52,33 @@ public class TeachersController {
@Autowired @Autowired
WebClient client; WebClient client;
@GetMapping("/teachers/resend") // @GetMapping("/teachers/resend")
public String infoResend(){ // public String infoResend(){
RestTemplate restTemplate = new RestTemplate(); // RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders(); // HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_PLAIN); // headers.setContentType(MediaType.TEXT_PLAIN);
HttpEntity<String> httpEntity = new HttpEntity<>(headers); // HttpEntity<String> httpEntity = new HttpEntity<>(headers);
ResponseEntity<String> response = // ResponseEntity<String> response =
restTemplate.exchange("http://resource-service-api:8181/teacher/list", HttpMethod.GET, httpEntity, String.class); // restTemplate.exchange("http://resource-service-api:8181/teacher/list", HttpMethod.GET, httpEntity, String.class);
return response.getBody(); // return response.getBody();
} // }
@GetMapping("/teachers") @GetMapping("/teachers")
public String listThy(Model model) throws JsonMappingException, JsonProcessingException{ public String listThy(Model model, @ModelAttribute("teachers") @Validated List<Teacher> teachers) throws JsonMappingException, JsonProcessingException{
Teacher teacher = new Teacher( String json = client.method(HttpMethod.GET)
2, "first_name", "second_name", "last_name", "employee_id", "snils" .uri("/teacher/list")
); .retrieve()
model.addAttribute("teacher", teacher); .bodyToMono(String.class)
.block();
RestTemplate restTemplate = new RestTemplate(); System.out.println("############################################################################");
ResponseEntity<String> response = System.out.println("############################################################################");
restTemplate.exchange("http://resource-service-api:8181/teacher/list", HttpMethod.GET, null, String.class); System.out.println("json :" + json);
String json = response.getBody();
ObjectMapper objectMapper = new ObjectMapper(); 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); model.addAttribute("teachers", teachers);
System.out.println("TEACHERS:" + teachers.toString());
return "teachers"; return "teachers";
} }
@ -105,7 +110,16 @@ public class TeachersController {
// return "teachers"; // return "teachers";
// } // }
// @PostMapping(path = "/teacher/add", consumes = {MediaType.APPLICATION_FORM_URLENCODED_VALUE}) /**
* Добавление сведений о преподавателе:
* - получение данных формы (в виде объекта teacher)
* - преобразование объекта teacher в json
* - отправка post запроса с данными json на сервис ресурсов
* - ожидание 1 секунду для уверенности, что запрос обработается сервером
* - направление пользователя на основную страницу
* @param teacher
* @return
*/
@PostMapping( @PostMapping(
path = "/teacher/add", path = "/teacher/add",
consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE,
@ -116,33 +130,57 @@ public class TeachersController {
client.post() client.post()
.uri("/teacher/create") .uri("/teacher/create")
.body(Mono.just(teacher), Teacher.class) .body(Mono.just(teacher), Teacher.class)
// .bodyValue(BodyInserters.fromValue(teacher))
.retrieve() .retrieve()
.toBodilessEntity() .toBodilessEntity()
.subscribe( .timeout(Duration.ofSeconds(1))
responseEntity -> { .block();
// Handle success response here return "redirect:/teachers";
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());
}
} }
);
// @GetMapping(path = "/teacher/delete/{id}")
// public String deleteTeacherByGet(@PathVariable Long id){
// client.delete()
// .uri("/teacher/delete/" + id)
// .retrieve()
// // .toBodilessEntity()
// .bodyToMono(String.class) // .bodyToMono(String.class)
// .timeout(Duration.ofSeconds(3)) // timeout // .timeout(Duration.ofSeconds(1))
// // .onErrorResume(e -> Mono.empty())
// .block(); // .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"; 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:
thymeleaf: thymeleaf:
enabled: true enabled: true
encoding: UTF-8 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">
<br> <br>
<h2>Добавление преподавателя:</h2> <h2>Добавление преподавателя:</h2>
<form th:action="@{/teacher/add}" method="post" th:object="${teacher}"> <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> <div>
<label>firstname</label> <label>Фамилия: </label>
<input type="text" th:field="*{first_name}" placeholder="string" /> <input type="text" th:field="*{first_name}" placeholder="" />
</div> </div>
<div> <div>
<label>secondname</label> <label>Имя: </label>
<input type="text" th:field="*{second_name}" placeholder="string" /> <input type="text" th:field="*{second_name}" placeholder="" />
</div> </div>
<div> <div>
<label>lastname</label> <label>Отчество: </label>
<input type="text" th:field="*{last_name}" placeholder="string" /> <input type="text" th:field="*{last_name}" placeholder="" />
</div> </div>
<div> <div>
<label>Табельный номер</label> <label>Табельный номер</label>
<input type="text" th:field="*{employee_id}" placeholder="string" /> <input type="text" th:field="*{employee_id}" placeholder="" />
</div> </div>
<div> <div>
<label>СНИЛС</label> <label>СНИЛС</label>
<input type="text" th:field="*{snils}" placeholder="string" /> <input type="text" th:field="*{snils}" placeholder="" />
</div> </div>
<input type="submit" value=обавить"/> <input type="submit" value=ОБАВИТЬ"/>
</form> </form>
<br> <br>
@ -54,18 +50,35 @@ xmlns:th="http://www.thymeleaf.org">
<th>lastname</th> <th>lastname</th>
<th>Табельный номер</th> <th>Табельный номер</th>
<th>СНИЛС</th> <th>СНИЛС</th>
<!-- <th>save</th> -->
<th>delete</th> <th>delete</th>
</tr> </tr>
<tr th:each="teacher: ${teachers}"> <tr th:each="teacher: ${teachers}" th:object="${teacher}">
<td th:text="${teacher.id}" /> <td>
<td th:text="${teacher.first_name}" /> <input type="text" th:field="${teacher.id}" placeholder="${teacher.id}"/>
<td th:text="${teacher.second_name}"></td> </td>
<td th:text="${teacher.last_name}"></td> <td>
<td th:text="${teacher.employee_id}"></td> <input type="text" th:field="${teacher.first_name}" placeholder="${teacher.first_name}"/>
<td th:text="${teacher.snils}"></td> </td>
<!-- <td>+</td> --> <td>
<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> </tr>
</table> </table>
</div> </div>

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

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

Loading…
Cancel
Save