Добавить часы работы ресторана java весна один ко многим - PullRequest
0 голосов
/ 19 января 2020

BACKEND: вот мой бэкэнд класса RestraurantService CreateRestaurantclass, у которого есть список часы работы:

public void createRestaurant(@Valid RestaurantCreateRequest restaurantCreateRequest){
        String email = SecurityContextHolder.getContext().getAuthentication().getName();
        RestaurantOwner restaurantOwner = restaurantOwnerService.findByEmail(email);
        boolean restaurantAlreadyExistWithThisName = restaurantAlreadyExistWithThisName(restaurantCreateRequest.getRestaurantName(),restaurantOwner.getId());
        if (restaurantAlreadyExistWithThisName){
            throw new RestaurantNotCreatedException("This name already exists, cannot create, please choose another one");
        }

        List<OpeningHours> openingHours = new ArrayList<>();
        List<OpeningHoursCreateRequest> openingHoursRequest = restaurantCreateRequest.getOpeningHoursList();
        for (OpeningHoursCreateRequest openingHoursCreateRequest : openingHoursRequest) {
            openingHours.add(OpeningHours.builder()
                    .withDay(openingHoursCreateRequest.getDay())
                    .withStartingHours(openingHoursCreateRequest.getStartingHours())
                    .withClosingHours(openingHoursCreateRequest.getClosingHours())
                    .build());
        }
        UUID uuid = UUID.randomUUID();
        Restaurant restaurant = Restaurant.builder()
                .withUuid(uuid)
                .withRestaurantName(restaurantCreateRequest.getRestaurantName())
                .withRestaurantOwner(restaurantOwner)
                .withOpeningHours(openingHours)
                .build();
        restaurantRepository.save(restaurant);
    }

BACKEND CONTROLLER: вот мой бэкэнд-контроллер метод createRestaurant

@PostMapping("/restaurants")
public void createRestaurant( @RequestBody RestaurantCreateRequest restaurantCreateRequest) throws IOException {
        restaurantService.createRestaurant(restaurantCreateRequest);
    }

Вот json на месте

{
    "restaurantName" : "test restfeo",
    "openingHoursList" : [
        {
        "day" : "Monday",
        "startingHours" : "12:00",
        "closingHours" : "22:00"    
        },
        {
        "day" : "Tuesday",
        "startingHours" : "12:00",
        "closingHours" : "22:00"

        }
        ,
        {
        "day" : "Wednessay",
        "startingHours" : "12:00",
        "closingHours" : "22:00"

        },
        {
        "day" : "Thursday",
        "startingHours" : "12:00",
        "closingHours" : "22:00"

        },
        {
        "day" : "Friday",
        "startingHours" : "12:00",
        "closingHours" : "22:00"

        },
        {
        "day" : "Saturday",
        "startingHours" : "12:00",
        "closingHours" : "22:00"

        },
        {
        "day" : "Sunday",
        "startingHours" : "12:00",
        "closingHours" : "22:00"

        },
        {
        "day" : "closed",
        "startingHours" : "closed",
        "closingHours" : "closed"

        }

        ]
}

** пока здесь все работает очень хорошо, я могу дать список часов работы контроллеру, который можно добавить данные в базу данных **

НО

прошло более недели, я пытаюсь отправить данные с html на json и он не работает Действительно нужна помощь

здесь моя клиентская кодировка

** Вот клиентская сторона: Ресторан клиент **

public Optional<String> createRestaurant(RestaurantCreateRequest restaurantCreateRequest) throws IOException {
        try {
            restTemplate.postForEntity(backendHost + "restaurants", restaurantCreateRequest, null);
        } catch (HttpClientErrorException e) {
            return Optional.of(ErrorMessageMapper.getErrorMessage(e));
        }
        return Optional.empty();
    }

** Вот контроллер ресторана **

 @PostMapping("/restaurants")
    public String addRestaurantToRestaurantOwner(Model model,
                                                 @Valid @ModelAttribute("restaurantCreateRequest") RestaurantCreateRequest restaurantCreateRequest,
                                                 BindingResult bindingResult, HttpSession httpSession) throws IOException {
        if (bindingResult.hasErrors()) {
            return "restaurants/create-restaurant";
        }
        Optional<String> error = restaurantClient.createRestaurant(restaurantCreateRequest);
        if(error.isPresent()){
            model.addAttribute("nameError", true);
            return "restaurants/create-restaurant";
        }

        return "redirect:/restaurantOwner/restaurantOwner-dashboard";
    }

** Я также пытался сохранить данные часов работы в сеансе http, но мне не удалось **

@PostMapping("/addOpeningHoursToList")
    public String add(Model model, @Valid @ModelAttribute("restaurantCreateRequest") RestaurantCreateRequest restaurantCreateRequest, HttpSession httpSession, BindingResult bindingResult) {

        httpSession.setAttribute("openingHours", new RestaurantCreateRequest().getOpeningHoursList());
        return "restaurant/create-restaurant";

    }

** находка Html **


<form th:action="@{/restaurants}" method="post">
                <div>
                    <label for="restaurantName">Restaurant name:</label>
                    <input type="text" id="restaurantName"  th:field="${restaurantCreateRequest.restaurantName}" required>
                    <span th:if="${nameError}">Restaurant already in use</span>
                </div>
            </form>
            <form id="list" action="@{/addOpeningHoursToList}">
                <div>
                    <h>Opening Hours</h>
                </div>
                <div>
                    <div>
                        <select type="text" id="day" name="day" th:text="${#httpSession.openingHours}">
                            <option>Monday</option>
                            <option>Tuesday</option>
                            <option>Wednesday</option>
                            <option>Thursday</option>
                            <option>Friday</option>
                            <option>Saturday</option>
                            <option>Sunday</option>
                        </select>
                    </div>
                    <div>
                        <input type="text" id="openingHours" name="openingHours" th:field="${httpSession.openingHours.openingHours}">
                    </div>
                    <div>
                        <input type="text" id="closingHours" name="closingHours" th:field="${httpSession.openingHours.closingHours}">
                    </div>
                    <div>
                        <input type="submit" value="Submit">
                    </div>
                </div>
            </form>

Заранее спасибо за вашу помощь ::: Я не могу создать список ресторанных часов и передать его контролеру

...