@Espio

Как оставить пустые поля для редактирования?

В Java ещё чайник. Делаю веб-приложение по гайдику, но подстраиваю некоторые моменты под себя. Столкнулся с проблемой. Для редактирования значений в БД я использую следующий метод.
@PreAuthorize("hasAuthority('ADMIN')")
    @PostMapping("/games/edit/{game}")
    public String updateGame(
            @PathVariable Long game,
            @RequestParam("idGame") Games games,
            @RequestParam String nameGame,
            @RequestParam int minCountPlayers,
            @RequestParam int maxCountPlayers,
            @RequestParam int minTime,
            @RequestParam int maxTime,
            @RequestParam String dynamics,
            @RequestParam String type,
            @RequestParam String complexity,
            @RequestParam int analysis,
            @RequestParam String description,
            @RequestParam ("file") MultipartFile file
           ) throws IOException {

        
        if (!StringUtils.isEmpty(nameGame)){
            games.setNameGame(nameGame);
        }

       if (!StringUtils.isEmpty(minCountPlayers)){
            games.setMinCountPlayers(minCountPlayers);
        }

        if (!StringUtils.isEmpty(maxCountPlayers)){
            games.setMaxCountPlayers(maxCountPlayers);
        }

        if (!StringUtils.isEmpty(minTime)){
            games.setMinTime(minTime);
        }

        if (!StringUtils.isEmpty(maxTime)){
            games.setMaxTime(maxTime);
        }

        if (!StringUtils.isEmpty(dynamics)){
            games.setDynamics(dynamics);
        }

        if (!StringUtils.isEmpty(type)){
            games.setType(type);
        }

        if (!StringUtils.isEmpty(complexity)){
            games.setComplexity(complexity);
        }

        if (!StringUtils.isEmpty(analysis)){
            games.setAnalysis(analysis);
        }


        if (!StringUtils.isEmpty(description)){
            games.setDescription(description);
        }


        if (file != null && !file.getOriginalFilename().isEmpty()) {
            File uploadDir = new File(uploadPath);

            if (!uploadDir.exists()) {
                uploadDir.mkdir();
            }

            String uuidFile = UUID.randomUUID().toString();
            String resultFilename = uuidFile + "." + file.getOriginalFilename();

            file.transferTo(new File(uploadPath + "/" + resultFilename));

            games.setFilename(resultFilename);
        }

        gamesRepo.save(games);

        return "redirect:/games/"+game;
    }


Задача следующая. Я в форме хочу отредактировать только одно поле, а не все сразу. Для значений типа String используется следующая конструкция
if (!StringUtils.isEmpty(nameGame)){
            games.setNameGame(nameGame);
        }

Как сделать тоже самое, только для значений типа int? При попытке сохранить изменения с пустыми полями в таком виде мне выдаётся ошибка.
There was an unexpected error (type=Bad Request, status=400).
Failed to convert value of type 'java.lang.String' to required type 'int'; nested exception is java.lang.NumberFormatException: For input string: ""
org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'int'; nested exception is java.lang.NumberFormatException: For input string: ""
	at org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver.resolveArgument(AbstractNamedValueMethodArgumentResolver.java:133)
  • Вопрос задан
  • 88 просмотров
Решения вопроса 1
@Kot1que
пишу на жаве
Попробуйте так:
@RequestParam(required=false, defaultValue="-1") int minTime
...
if (minTime < 0) {

}
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы