【问题标题】:Spring Mvc/Jpa-OneToMany : How to display a list of class associated to another oneSpring Mvc/Jpa-OneToMany:如何显示与另一个关联的类列表
【发布时间】:2012-08-12 15:13:40
【问题描述】:

我有一个带有 OneToMany 绑定的类 Module 和类序列。 我的目标是显示模块列表,并通过单击其中一个,显示相关的序列列表 但它不起作用,我有一个 HTTP 500 错误。

这是我的控制器:

@RequestMapping(value="formation", method = RequestMethod.GET)
public ModelAndView allModules() {
List<Module> allModules = moduleService.findAll();
return new ModelAndView("formation", "modules", allModules);
}

@RequestMapping(value="sequences/{module}", method = RequestMethod.GET)
public String displaySequences(@PathVariable ("module") Module module, Model model) {
List<Sequence> allSequences = sequenceService.findByModule(module);
model.addAttribute("sequences", allSequences);
return "sequences";
}

和显示模块列表的jsp返回序列列表

<c:forEach items="${modules}" var="module">
            <ul>
                <li><a href="sequences/${module}">${module.titre}</a>
                    <br/>
                </li>
            </ul>
        </c:forEach>

那么,我的错误来自哪里?

当我这样做时它会起作用:

    @RequestMapping(value="/sequences/{moduleId}", method = RequestMethod.GET)
public String displaySequences(@PathVariable ("moduleId") Long moduleId, Model model) {
Module module = moduleService.findById(moduleId);
model.addAttribute("module", module);
return "sequences";
}

我用 :

更改链接
<a href="sequences/${module}">${module.titre}

但我想了解我的错误。

【问题讨论】:

  • 你看到 JSP 代替 ${module} 渲染了什么吗?
  • 是一种代码 /myAppli/sequences/com.almerys.jpa.tomcatspring.Module@12b0f0ae 其中 com.almerys.jpa.tomcatspring 是模块类所在的包。

标签: jpa spring-mvc one-to-many


【解决方案1】:

你不能显示序列的原因是 Spring 不知道如何解析这个

/cmap-web/sequences/com.almerys.jpa.tomcatspring.Module@12b0f0ae

进入模块实例。

您可以在该部分的 16.3.2.2 URI Template Patterns 最后一段中的 Spring 文档 here 中阅读此内容。为了方便,我把它贴在这里。

@PathVariable 参数可以是任何简单类型,例如 int、long、Date 等。Spring 会自动转换为适当的类型,或者如果它失败则抛出 TypeMismatchException。您还可以注册对解析其他数据类型的支持。请参阅第 16.3.3.14 节,“方法参数和类型转换”和第 16.3.3.15 节,“自定义 WebDataBinder 初始化”。

【讨论】:

  • 我可能做得不好,因为我想通过在阅读第 16.3.2.2 节 URI 模板模式和here 中的 Spring 文档后将 @InitBinder public void initBinder(WebDataBinder binder) { binder.registerCustomEditor(Module.class, new PropertiesEditor()); } 添加到我的控制器中来将模块类转换为字符串,但现在我有一个 HTTP 400 错误。怎么了?
  • 我尝试了thisthis 的混合,但我有一个白页
  • 我以为这是默认方法,所以我就这么写了。之后,我将 PropertiesEditor 更改为 ModuleEditor ,其代码为 public class ModuleEditor extends PropertyEditorSupport { private final Module module; /****constructor*** @Override public void setAsText(String text) throws IllegalArgumentException { setValue(module); } } 但我认为问题来自 Spring Data Jpa。我使用它,但我不知道预期的客户价值(在我的情况下是模块价值)。如果您考虑更简单的解决方案,我将不胜感激。
  • 我建议使用this 解决方案。您之前发布的那个。
  • 还是不行。我认为问题来自countryService.get(Long.parseLong(text)) 行,因为我无法在 ModuleService 中定义一个方法 get 来返回一个不是其 ID 的数字的模块。我尝试了一切,但一切都失败了,所以我想我会做不同的
猜你喜欢
  • 1970-01-01
  • 2011-06-22
  • 2015-06-05
  • 1970-01-01
  • 1970-01-01
  • 2023-01-25
  • 2019-10-20
  • 2014-11-16
  • 1970-01-01
相关资源
最近更新 更多