ошибка при добавлении проверок весенней загрузки на тимилиф - PullRequest
0 голосов
/ 30 марта 2019

Я делаю проект в весенней загрузке и использую тимилиф для html.Я должен поставить проверку на поле из класса модели с именем «currentTemp», который имеет тип Float.Таким образом, проблема заключается в первой перезагрузке программы, и я получаю обновление погоды, но затем, когда я нажимаю кнопку «Добавить» на веб-сайте, чтобы добавить погоду в базу данных, возникает проблема с файлом шаблона

Weather.java

@Entity
@Table(name="weather", uniqueConstraints = @UniqueConstraint(columnNames = {"city"}))
@Data
public class Weather {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private Long id;

    @Column(name = "city")
    private String city;

    private String headline;

    @Column(name = "descriptions")
    private String description;

    @Transient
    private String wind;

    @Transient
    private String icon;


    @Range(min=0, max=100, message = "length should be less than 100")
    private float currentTemp;


    private String minTemp;
    private String maxTemp;
    private String sunrise;
    private String sunset;

    @Transient
    private String unit;
}

Затем у меня есть класс контроллера, который выглядит следующим образом:

 @PostMapping("/checkWeather")
    public String doActions(@ModelAttribute @Valid Weather weather,
                            BindingResult result, @RequestParam String action,
                            Map<String,Object> map, Errors errors, Model model)
                throws IOException {
        if(action.equals("add")){
            if(errors.hasErrors()){
                map.put("weatherList",crudService.getAllWeatherList());
                model.addAttribute("weather",weather);
                return "weather-history";
            }
            crudService.add(weather);
}

@GetMapping("/checkWeather")
public String checkWeather(@RequestParam(name="city", required=true, defaultValue="Oops! you typed wrong url!")
                                       String city, Map<String,Object> map, Model model)
        throws IOException,HttpClientErrorException.NotFound {
    try{
        Weather result = getWeatherService.getNewWeatherObject(city);
        String timeConvertedSunrise = convertMillisecondsService.convertToTime(Long.parseLong(result.getSunrise()));
        String timeConvertedSunset = convertMillisecondsService.convertToTime(Long.parseLong(result.getSunset()));
        map.put("weatherList",crudService.getAllWeatherList());
        model.addAttribute("weather",result);
        model.addAttribute("weatherMap",map);
        model.addAttribute("city",city.substring(0,1).toUpperCase()+city.substring(1));
        model.addAttribute("headline", result.getHeadline());
        model.addAttribute("description", result.getDescription());
        model.addAttribute("icon", result.getIcon());
        model.addAttribute("wind", result.getWind());
        model.addAttribute("currentTemp", result.getCurrentTemp());
        model.addAttribute("minTemp", result.getMinTemp());
        model.addAttribute("maxTemp", result.getMaxTemp());
        model.addAttribute("sunrise", timeConvertedSunrise);
        model.addAttribute("sunset", timeConvertedSunset);
        model.addAttribute("unit", result.getUnit());
    }catch (HttpClientErrorException e){
        LOGGER.info("Typed City cannot be found, please type name correctly! Aborting program..");
        return "notfound";
    }
    return "weather-history";
}

Здесь я пытаюсь добавить запись в таблицу в соответствии с пользователем при нажатии на "Кнопка «Добавить» в интерфейсе веб-приложения.Но перед добавлением записи я хочу проверить поле, как показано в html-файле ниже:

weather-history.html

<!-- City search form and button -->
<div class="search-wrapper">
<form class="navbar-form" th:action="@{/checkWeather}" method="get">
    <div class="row">
        <div class="col-lg-8">
            <input type="text" name="city" class="form-control" placeholder="Type the name of the city..">
        </div>
        <div class="col-sm-4">
            <button type="submit" class="btn btn-primary">Search Weather</button>
        </div>
    </div>
</form>
</div>
    <!-- history table -->
    <div class="jumbotron" id="history-table">
    <div class="crud-form-field">
        <form class="crud-form"  th:action="@{/checkWeather}" th:object="${weather}" method="post">
            <div class="form-group">
                <input type="text" name="city" class="form-control" th:value="${city}" placeholder="Enter City" />
                <input type="text" name="headline" class="form-control" th:value="${headline}" placeholder="Enter Headline" />
                <input type="text" name="description" class="form-control" th:value="${description}" placeholder="Enter Description" />
                <input type="text" name="currentTemp" class="form-control" th:value="${currentTemp}" placeholder="Enter Current Temp" th:field="*{currentTemp}" />
                <p th:if="${#fields.hasErrors('currentTemp')}" th:errors="*{currentTemp}"></p>
                <input type="text" name="minTemp" class="form-control" th:value="${minTemp}" placeholder="Enter Min Temp" />
                <input type="text" name="maxTemp" class="form-control" th:value="${maxTemp}" placeholder="Enter Max Temp" />
                <input type="text" name="sunrise" class="form-control" th:value="${sunrise}" placeholder="Enter Sunrise" />
                <input type="text" name="sunset" class="form-control" th:value="${sunset}" placeholder="Enter Sunset" />
            </div>
            <div class="submit-crudform">
                <button type="submit" name="action" value ="add" class="btn btn-outline-success"><i class="fas fa-plus-circle"></i> Add</button>
                <button type="submit" name="action" value ="edit" class="btn btn-outline-success"><i class="far fa-edit"></i> Edit</button>
                <button type="submit" name="action" value ="update" class="btn btn-outline-success"><i class="fas fa-sync"></i> Update</button>
                <button type="submit" name="action" value ="delete" class="btn btn-outline-success"><i class="fas fa-trash-alt"></i> Delete</button>
            </div>
        </form>
    </div>

Но, тем не менее, оно выдает ошибкусвязанный с шаблоном тимелина, который говорит:

org.springframework.expression.spel.SpelEvaluationException: EL1011E: Method call: Attempted to call method get(java.lang.String) on null context object
    at org.springframework.expression.spel.ast.MethodReference.throwIfNotNullSafe(MethodReference.java:153) ~[spring-expression-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.expression.spel.ast.MethodReference.getValueRef(MethodReference.java:82) ~[spring-expression-5.1.5.RELEASE.jar:5.1.5.RELEASE]

Я думаю, что-то связано со строками, где я пытаюсь проверить поля ввода, которые:

<input type="text" name="currentTemp" class="form-control" th:value="${currentTemp}" placeholder="Enter Current Temp" th:field="*{currentTemp}" />
            <p th:if="${#fields.hasErrors('currentTemp')}" th:errors="*{currentTemp}"></p>

Если я удаляю эти дополнительныеПараметры для проверки ошибки, проблема решена.

Я попытался прочитать о тимелист, но мой синтаксис неверный.Я следил за некоторыми видео на YouTube, и они также применили проверку к шаблону таким же образом, как и я.Чего я не понимаю, так это того, что трассировка стека мне не совсем понятна.Там написано all method get(java.lang.String) on null context object, так какое поле показывает нулевое значение?не в состоянии понять.

Не могли бы вы направить меня в правильном направлении.мне кажется, что мне не хватает только очень маленького фрагмента головоломки.

EDIT

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

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...