не может просматривать записи, хранящиеся в БД на веб-странице - PullRequest
0 голосов
/ 05 июля 2018

Я имею в виду это руководство (http://jvmhub.com/2015/08/09/spring-boot-with-thymeleaf-tutorial-part-3-spring-data-jpa/), единственное отличие в том, что я объединил классы PostEntity и Post, приняв имя PostEntity.

Когда я пытаюсь сохранить данные в БД через форму, приложения работают, но это не позволяет мне просматривать сохраненные данные на веб-странице, как показано в руководстве, указанном выше. Веб-страница result.html отображается как

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

Thu Jul 05 14:25:42 CEST 2018
There was an unexpected error (type=Internal Server Error, status=500).
Exception evaluating SpringEL expression: "PostEntity.title" (template: "result" - line 11, col 9)"

и консоль показывает исключение:

org.springframework.expression.spel.SpelEvaluationException: EL1007E: Свойство или поле 'title' не может быть найдено в null

Он генерируется даже с другими атрибутами (идентификатором и содержимым) в соответствии с порядком их расположения в файле result.html.

Если я пытаюсь распечатать содержимое переменной записи в консоли, это показывает, что оно не равно нулю, поэтому я не могу понять, почему существует это исключение.

Контроллер:

@Controller

public class Home {
@Autowired  private PostRepository  postRepository; 

@RequestMapping(value="/", method=RequestMethod.GET)
public String index(Model model) {
    model.addAttribute("post", new PostEntity());
    return "index";
}

@RequestMapping(value = "/", method = RequestMethod.POST)
public String addNewPost( PostEntity post, BindingResult bindingResult, Model model) {
    if (bindingResult.hasErrors()) {
        return "index";
    }

    postRepository.save(post);
    List<PostEntity> records = (List<PostEntity>) postRepository.findAll();

    model.addAttribute("posts", records);
            return "redirect:result";
}

 @RequestMapping(value = "/result", method = RequestMethod.GET)
public String showAllPosts(Model model) {
     List<PostEntity> records = (List<PostEntity>) postRepository.findAll();
        for (PostEntity record : records) {
            System.out.println(record);
        }
    model.addAttribute("posts",  records);
    return "result"; 
 }
}   

Класс модели:

@Entity
public class PostEntity {

public PostEntity() {}

public PostEntity(String title, String content) {
    this.title = title;
    this.content = content;
}

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public int id;

public String title;

public String content;

public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}
public String getTitle() {
    return title;
}
public void setTitle(String title) {
    this.title = title;
}
public String getContent() {
    return content;
}
public void setContent(String content) {
    this.content = content;
}
}

Индекс:

    <!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Spring Boot and Thymeleaf example</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
    <h3>Spring Boot and Thymeleaf, part 2 - forms</h3>
    <form action="#" th:action="@{/}" th:object="${post}" method="post">
        <table>
            <tr>
                <td>Title:</td>
                <td><input type="text" th:field="*{title}" /></td>
                <td th:if="${#fields.hasErrors('title')}" th:errors="*{title}">Title error message</td>
            </tr>
            <tr>
                <td>Content:</td>
                <td><input type="text" th:field="*{content}" /></td>
                <td th:if="${#fields.hasErrors('content')}" th:errors="*{content}">Content error message</td>
            </tr>
            <tr>
                <td><button type="submit">Submit post</button></td>
            </tr>
        </table>
    </form>
</body>
</html>

результат

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Spring Boot and Thymeleaf example</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
    <h3>Spring Boot and Thymeleaf, part 3 - SPRING DATA JPA</h3>
    <p th:each="PostEntity : ${posts}">
        <h4>Title:</h4>
         <div th:text="${PostEntity.title}"/></div>
        <h4>ID:</h4>
         <div th:text="${PostEntity.id}"/></div>
        <h4>Content:</h4>
         <div th:text="${PostEntity.content}"/></div>
        <div>---------------------------------------------------------</div>
    </p>
</body>
</html>

Есть предложения?

1 Ответ

0 голосов
/ 05 июля 2018

Вы делаете эту вещь перенаправления. При этом ваши объекты, добавленные в модель, не достигают дальнейшего процесса. Я помню, как столкнулся с подобной проблемой.

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