java - 为什么 Spring Boot MVC 总是从我的表单返回 null 值?

标签 java mysql spring thymeleaf

我研究了好几天,但没有一个对我有用。我从网上得到的大部分都是jsp,但我使用的是Thymeleaf。我想要编写的是通用类型的 CRUD,它接受任何类及其变量以成为 View 页面的字段标签和输入。

但是,每次我尝试提交填写的表单时,它都会保存在数据库中,但只有 ID 不为空,其他均为空值。

这是我的方法,它带有 @ModelAttribute 注释:

@ModelAttribute
public void instantiateEntity(Model model,
      @RequestParam("entityName") String entityName)
      throws Exception {

String className = SimpleEntity.NAMEPREF + entityName;
SimpleEntity entity =
        (SimpleEntity) Class.forName(className).getDeclaredConstructor().newInstance();

 Field[] fields = Class.forName(className).getDeclaredFields();
 List<FieldUI> fieldUISpecs = new ArrayList<>();

   for (Field f : fields) {
     System.out.println(f.getName());
     FieldUI fieldUI = new FieldUI(f);
     UI ui = f.getAnnotation(UI.class);
     if (ui != null){
       fieldUI.setColHeading(ui.colHeading());
       fieldUI.setFldPrompt(ui.fldPrompt());
       fieldUI.setCss(ui.css());
       fieldUI.setInputHidden(ui.inputHidden());
       fieldUI.setColHidden(ui.colHidden());
       fieldUI.setType(ui.type());

       if(!ui.option().equals("")){
        fieldUI.setOption(entityDBA.listEntities(ui.option()));
        System.out.println(fieldUI.getOption());
       }

       System.out.println("\n --- CSS: "+fieldUI.getCss());

    } else {
      fieldUI.setColHeading(f.getName());
      fieldUI.setFldPrompt(f.getName());
      fieldUI.setColHidden(false);
      fieldUI.setInputHidden(false);

    }
    fieldUISpecs.add(fieldUI);
  }

  List<SimpleEntity> entities = entityDBA.listEntities(entityName);

  model.addAttribute("fieldUISpecs", fieldUISpecs);
  model.addAttribute("entity", entity);
  model.addAttribute("entities", entities);
  model.addAttribute("currentEntity", entityName);
  model.addAttribute("displayAddButton", true);
  model.addAttribute("displayList", true);

 }

这是我用于保存的 Controller :

@PostMapping("/add") 
public String addEntity(@Valid @ModelAttribute("entity") SimpleEntity entity, BindingResult result, Model model, @RequestParam("entityName") String entityName){

    List<SimpleEntity> entities = db.listEntities(entityName);
    model.addAttribute("displayList", true);
    System.out.println("Entity values: "+entityName);

    if (result.hasErrors()) {
      model.addAttribute("displayForm", true);
      model.addAttribute("isNew", true);

      return "th_home";
    }

    db.saveEntity(entity);

    return "redirect:/list-edit-entities?entityName="+entityName;}

    //Here's my transactional or service layer:

    public long saveEntity(SimpleEntity entity) {
        long id = 0;
        Session ses = sf.getCurrentSession();
        if (entity.getId() == 0) ses.persist(entity);
        else ses.merge(entity);
        return entity.getId();
    }

这是我的观点:

<form th:if="${isNew}" method="POST" th:action="@{'/add?entityName='+${currentEntity}}" th:object="${entity}">
<th:block th:each="field: ${fieldUISpecs}">
    <div class="input-group" th:unless="${field.inputHidden}">
      <label th:unless="${field.name} == 'id'" th:text="${field.name}"></label>

        <input type="hidden" th:if="${field.name} == 'id'" class="c-form" th:field="*{__${field.name}__}" readonly>
        <input th:type="${field.type}" th:unless="${field.name} == 'id'" class="c-form" th:field="*{__${field.name}__}">
      </th:block>
    </div>
  </th:block>
  <div class="input-group input-button">
    <input class="save-button" type="submit" value="Save">
  </div>
</form>

最佳答案

您正在使用@ModelAttribute,这就是您在提交后在 Controller 上收到空值的原因。

在请求查看页面的 Controller 上,您需要发送 SimpleEntity 对象。

对于例如。 -

第 1 步 -

@RequestMapping("/openRequestedPage")
   public String addReferralPack(Model model) { 
   model.addAttribute("simpleEntityObject", new SimpleEntity());
   return "openRequestedPage";
} 

第 2 步 -

<form th:if="${isNew}" method="POST" th:action="@{'/add?entityName='+${currentEntity}}"  th:object="${simpleEntityObject}"">

     //Some Code

</form>

第3步

@PostMapping("/add") 
public String addEntity(@Valid @ModelAttribute("simpleEntityObject") SimpleEntity entity, BindingResult result, Model model, @RequestParam("entityName") String entityName){

     //some code
     return "yourPageName";

}

有关 @ModelAttribute 的信息,这里有一个链接 -

What is @ModelAttribute in Spring MVC?

这是有关其工作原理的引用 -

https://www.baeldung.com/spring-mvc-and-the-modelattribute-annotation][1]

关于java - 为什么 Spring Boot MVC 总是从我的表单返回 null 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57921219/

相关文章:

java - 间歇性奇怪的 tomcat 问题部署 war 文件

java - 哪些 Jackson maven 依赖项包含在 spring 3.1 项目中以进行 JAXB JSON 编码?

php - 用 PHP 替换\r\n

java - 在@bean 工厂方法上使用自定义注解

java - 使用 jackson 序列化通用 JSON

java - 从线程内部调用时 Spring 数据存储库 find 方法挂起

写入字节数组时出现java.lang.NullPointerException

java - 在 Intellij IDEA 中打开 Gradle 项目时出现问题

php - 如何使用 php 和 javascript 从 mysql 中删除行

mysql - 我的表是什么 ROW_FORMAT?