【问题标题】:Why does Spring Boot MVC always return null values from my form?为什么 Spring Boot MVC 总是从我的表单返回空值?
【发布时间】:2020-01-15 04:30:25
【问题描述】:

我已经研究了好几天,但没有一个对我有用。我从 Internet 上得到的大部分是 jsp,但我使用的是 Thymeleaf。我正在尝试编写的是一种通用类型的 CRUD,它接受任何类及其变量来成为视图页面的字段标签和输入。

但是,每次我尝试提交填写的表格时,它都会保存在数据库中,但只有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);

 }

这是我用于保存的控制器:

@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>

【问题讨论】:

    标签: java mysql spring thymeleaf


    【解决方案1】:

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

    在您请求查看页面的控制器上,您需要发送 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]

    【讨论】:

    • 是的,我正在使用 @ModelAttribute,但是如果我尝试在 @Postmapping("/add") 上删除它,则在系统运行时,整个添加部分将无法正常工作。我只想获取用户的输入值,但我不知道如何。 ://
    • 编辑了我的答案,请看一下。希望对您有所帮助。
    • 嗨@Sumit 谢谢你的时间。我尝试了你所说的关于发送我的 SimpleEntity 对象的内容,但它要求我始终实现方法。我不确定我是否应该在我的 @ModelAttribute 实例化方法或我写的表单开启器方法上写这个 new SimpleEntity()
    • 我编辑了我的问题@Sumit,这样您就可以看到提交表单时所有值在哪里重置为空。
    • 对象的引用名称在任何地方都必须相同 - 在控制器和表单上也是如此。请检查“SimpleEntity”对象引用名称。
    猜你喜欢
    • 2019-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多