繁体   English   中英

Spring 提交表单后的空对象(H2、SpringBoot、Thymeleaf、CRUD)

[英]Null Objects after submitting Form in Spring (H2, SpringBoot, Thymeleaf, CRUD)

我正在创建一个 Spring Boot 应用程序,用户可以在其中创建许可证。 用户可以键入名称、购买日期、续订日期和到期日期。

我的问题是,当我尝试保存数据时,它会为名称、购买日期、续订日期和到期日期返回 null。

我完全不知道该怎么办了,请帮忙。 Model:Licence 中的“// Comment”值是在执行帖子时为空的值。

型号:许可证

@Entity
@Table(name = "TBL_LICENCES")
public class Licence {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long Id;
    private String licenceName;  // --> null after the post
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private String purchaseDate; // --> null after the post
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private String renewalDate; // --> null after the post
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private String expirationDate; // --> null after the post

    public Licence() {}
    public Licence(Long id, String licenceName, String purchaseDate, String renewalDate, String expirationDate) {
        Id = id;
        this.licenceName = licenceName;
        this.purchaseDate = purchaseDate;
        this.renewalDate = renewalDate;
        this.expirationDate = expirationDate;
    }

    // Getter and Setter
}

模型:LicenceRepository

@Repository
public interface LicenceRepository extends CrudRepository<Licence, Long> { }

服务:LicenceService

@Service
public class LicenceService {
    @Autowired
    private LicenceRepository licenceRepository;

    public List<Licence> getLicences() {
        return (List<Licence>) licenceRepository.findAll();
    }

    public Optional<Licence> getLicenceById(Long id) {
        return licenceRepository.findById(id);
    }

    public void addLicence(Licence licence) {
        licenceRepository.save(licence);
    }

    public void updateLicence(Licence licence) {
        licenceRepository.save(licence);
    }

    public void deleteLicenceById(Long id) {
        licenceRepository.deleteById(id);
    }
}

控制器:LicenceController

@Controller
public class LicenceController {
    @Autowired
    private LicenceService licenceService;

    @GetMapping("/licences")
    public String getLicences(Model model) {
        model.addAttribute("licences", licenceService.getLicences());
        return "licences";
    }

    @GetMapping("/onelicence")
    @ResponseBody
    public Optional<Licence> getLicenceByID(Long id, Model model) {
        model.addAttribute("onelicence", licenceService.getLicenceById(id));
        return licenceService.getLicenceById(id);
    }

    @RequestMapping(value="/save", method = {RequestMethod.POST, RequestMethod.PUT, RequestMethod.GET})
    public String updateLicence(Licence licence) {
        licenceService.updateLicence(licence);
        return "redirect:/licences";
    }

    **// Is performed, when clicking "New Licence > Save"**
    @RequestMapping(value="/addNew", method = {RequestMethod.POST, RequestMethod.PUT, RequestMethod.GET})
    public String addLicence(Licence licence) {
        licenceService.addLicence(licence);
        return "redirect:/licences";
    }

    @RequestMapping(value="/delete", method = {RequestMethod.DELETE, RequestMethod.PUT, RequestMethod.GET})
    public String deleteLicence(Long id) {
        licenceService.deleteLicenceById(id);
        return "redirect:/licences";
    }
}

许可证.html

<!DOCTYPE html>
<html lang="de" xmlns="http://www.w3.org/1999/html"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <script type ="text/javascript" src="webjars/jquery/3.4.1/jquery.min.js"></script>
    <script type ="text/javascript" src="webjars/bootstrap/4.4.1/js/bootstrap.min.js"></script>
    <link href="webjars/bootstrap/4.4.1/css/bootstrap.css" rel="stylesheet"/>
    <title>Licence</title>
</head>
<body>
<div class = "container">
    <h2>Licences</h2>
    <table class = "table table-striped">
        <thead>
            <tr>
                <td>ID</td>
                <td>Name</td>
                <td>Kaufdatum</td>
                <td>Erneuerungsdatum:</td>
                <td>Auslaufdatum:</td>
            </tr>
        </thead>
        <tbody>
            <tr th:each = "licence: ${licences}">
                <td th:text="${licence.id}">ID</td>
                <td th:text="${licence.licenceName}">Name</td>
                <td th:text="${licence.purchaseDate}">Kaufdatum</td>
                <td th:text="${licence.renewalDate}">Erneuerungsdatum</td>
                <td th:text="${licence.expirationDate}">Auslaufdatum</td>
                <td><a class="btn btn-warning">Edit</a></td>
                <td><a class="btn btn-danger">Delete</a></td>
            </tr>
        </tbody>
    </table>
    <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#addModal" data-whatever="@mdo">New Licence</button>
</div>

// Bootstrap Varying Modal Content

<div class="modal fade" id="addModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <form th:action="@{/addNew}" method ="post">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLabel">New Licence</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>

            <div class="modal-body">
                    <div class="form-group">
                        <label for="name" class="col-form-label">Lizenz Name</label>
                        <input type="text" class="form-control" id="licenceName" name="name">
                    </div>
                    <div class="form-group">
                        <label for="purchase" class="col-form-label">purchaseDate</label>
                        <input type="date" class="form-control" id="purchaseDate" name="purchase">
                    </div>
                    <div class="form-group">
                        <label for="renewalAdd" class="col-form-label">renewalDate</label>
                        <input type="date" class="form-control" id="renewalAdd" name="renewal">
                    </div>
                    <div class="form-group">
                        <label for="expirationAdd" class="col-form-label">expirationDate</label>
                        <input type="date" class="form-control" id="expirationAdd" name="expiration">
                    </div>
            </div>

            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                <button type="submit" class="btn btn-primary">Save</button>
            </div>

        </div>
    </div>
    </form>
</div>
</body>
</html>

模式.sql

DROP TABLE IF EXISTS TBL_LICENCES;

CREATE TABLE TBL_LICENCES (
  id INT AUTO_INCREMENT  PRIMARY KEY,
  licence_name VARCHAR(250),
  purchase_date VARCHAR(250),
  renewal_date VARCHAR(250),
  expiration_date VARCHAR(250)
);

data.sql --> 这有效并显示数据。

INSERT INTO
    TBL_LICENCES (licence_name, purchase_date, renewal_date, expiration_date)
VALUES
    ('Test1', '2020-01-31', '2020-06-31', '2020-12-31'),
    ('Test', '2021-01-31', '2021-06-31', '2021-12-31');

属性:application.properties

spring.h2.console.enabled=true
spring.datasource.platform=h2
spring.datasource.url=jdbc:h2:mem:<dbLicences>
spring.jpa.hibernate.ddl-auto=update

input控件的name属性应与Licence类中的字段名称相匹配。 目前您的id属性与字段的名称匹配,但是当提交表单时,它使用name属性来构建请求参数。

更新您的 HTML 以匹配以下内容:

<input type="text" class="form-control" id="licenceName" name="licenceName" />

修复其他字段的名称,您将使用表单中的数据填充Licence对象。

另外,我看到

@DateTimeFormat(pattern = "yyyy-MM-dd")
private String licenceName;

licenceName@DateTimeFormat注释。 我想这是一个错误,也请纠正。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM