Ошибка при передаче шаблона в Springboot - PullRequest
1 голос
/ 06 мая 2020

Я новичок в Springboot, и я столкнулся с этой ошибкой в ​​браузере:

Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.

Wed May 06 02:05:58 PDT 2020
There was an unexpected error (type=Internal Server Error, status=500).
An error happened during template parsing (template: "class path resource [templates/institute/home.html]" - line 29, col 28)

Код моего InstituteController:

package com.example.demo.controller;

import com.example.demo.dto.InstituteDto;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.validation.Valid;

@Controller
@RequestMapping("/institute")
public class InstituteController {

    @GetMapping("/home")
    private String instituteSave(Model model) {
        model.addAttribute("institute", new InstituteDto());
        return "institute/home";
    }

    @PostMapping("/save")
    private String saveInstitute(@Valid @ModelAttribute("institute") InstituteDto instituteDto, BindingResult bindingResult, RedirectAttributes redirectAttributes) {
        if (!bindingResult.hasErrors()) {
            return null;
        } else {
            String error = bindingResult.getAllErrors().get(0).getDefaultMessage();
            redirectAttributes.addFlashAttribute("error",error);
            return "redirect:/institute/home";
        }
    }
}

Код моего InstituteDto:

package com.example.demo.dto;

import com.example.demo.enums.Status;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.UniqueConstraint;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class InstituteDto {

    private Long id;
    @NotNull(message = "Institute name cannot be null")
    @NotBlank(message = "Institute name cannot be blank")
    private String name;
    @NotNull(message = "Institute address cannot be null")
    @NotBlank(message = "Institute address cannot be blank")
    private String address;
    @NotNull(message = "Institute officialWebsite cannot be null")
    @NotBlank(message = "Institute officialWebsite cannot be blank")
    private String officialWebsite;
    private Status status;
}

Код моего дома. html:

<!DOCTYPE html>
<html lang="en" xmlns:th="https://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Institute Home page</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
          integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-md-4">
            <h3>Form</h3>
            <!--/*@thymesVar id="institute" type="institute"*/-->
            <form th:action="@{~/institute/save}" method="post" th:object="${institute}">
                <div class="form-group">
                    <label for="institute_name">Institute name</label>
                    <input type="name" class="form-control" id="institute_name" aria-describedby="institute_name"
                           th:field="*{name}">
                </div>

                <div class="form-group">
                    <label for="address">Institute address</label>
                    <input type="name" class="form-control" id="address" aria-describedby="address" th:field="*{address}>
                    </div>

                    <div class=" form-group">
                    <label for="officialWebsite">Institute officialWebsite</label>
                    <input type="name" class="form-control" id="officialWebsite" aria-describedby="officialWebsite"
                           th:field="*{officialWebsite}>
                    </div>

                    <button type="submit" class="btn btn-primary">Submit</button>
                </form>
            </div>
            <div class=" col-md-8">
                    <h3>List</h3>
                </div>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"
            integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n"
            crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"
            integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo"
            crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"
            integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6"
            crossorigin="anonymous"></script>
</body>
</html>

Я нашел какое-то решение, и некоторые сказали изменить аннотацию контроллера на RestController, но это не решило мои проблема тоже.

Я пытаюсь привязать сообщение об ошибке на веб-странице, а также получить входные данные в модели с веб-страницы. Что вызывает эту ошибку и как ее исправить?

1 Ответ

1 голос
/ 06 мая 2020

Вы получаете сообщение об ошибке template parsing, потому что вы пропустили тег для закрытия дома. html

<input> тег в вашем файле не закрывается в строке 26. Закройте это и попробуйте снова запустить свой код.

<input type="name" class="form-control" id="officialWebsite" aria-describedby="officialWebsite"
                           th:field="*{officialWebsite}/>

Почему это происходит? - потому что все должно быть в действительном XML тимелеафе. Проверить История

и Ссылка

...