为什么我通过发布并发送到另一个页面来获取Spring中的null对象?

时间:2017-11-03 21:31:51

标签: java spring spring-mvc spring-boot

我正在玩提交Spring表单,现在我遇到了对象问题。它是空的。我不知道为什么。我决定使用System.out.println这个对象并获取所有数据,但是在将它发送到另一个页面之后它就是null。如何解决这个问题?

控制器

package com.megaproject3.MainProject.Controller;

import com.megaproject3.MainProject.Model.Book;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;

@Controller
public class BookController
{
    @GetMapping("/books/add")
    public String addBook(Model model)
    {
        model.addAttribute("newAddedBook", new Book());
        return "addNewBook";
    }

    @PostMapping("/books/view")
    public String wwnewBook(@ModelAttribute Book book)
    {
        System.out.println(book.getAuthor() + " || " + book.getTitle()); // IT WORKS - I GET DATA I TYPE
        return "result";
    }
}

addNewBook.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>Add New Book</title>
</head>
<body>

<form action="#" th:action="@{/books/view}" th:object="${newAddedBook}" method="post">
    <p>Title: <input type="text" th:field="*{title}"/></p>
    <p>Author: <input type="text" th:field="*{author}"/></p>
    <p>Genre: <input type="text" th:field="*{genre}"/></p>
    <input type="submit" value="Submit"/> <input type="reset" value="Reset"/>
</form>

</body>
</html>

result.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>Title</title>
</head>
<body>

<h2 th:text=" 'You have just added ' + ${newAddedBook}"></h2> // You have just added null

<a href="/books/add">Add another one book</a>

</body>
</html>

提前谢谢。

1 个答案:

答案 0 :(得分:0)

这是因为您没有为结果页面绑定获取的数据。 只需简单地绑定它。 @ModelAttribute只从页面中获取要在wwnewbook方法中使用的数据。它不会自动为结果页面绑定。这样做

@PostMapping("/books/view")
public String wwnewBook(@ModelAttribute Book book, Model model)
{
model.addAttribute("newAddedBook", book);
    System.out.println(book.getAuthor() + " || " + book.getTitle()); //     IT WORKS - I GET DATA I TYPE
    return "result";
}