【问题标题】:JSF, Spring and Hibernate - how to populate edit form with id GET paramJSF、Spring 和 Hibernate - 如何使用 id GET 参数填充编辑表单
【发布时间】:2015-09-24 12:06:06
【问题描述】:

我正在学习如何在我的 Web 应用程序中集成 JSF、Spring、Hibernate 的示例教程:

http://www.journaldev.com/7122/jsf-spring-hibernate-integration-example-tutorial

http://www.journaldev.com/3531/spring-mvc-hibernate-mysql-integration-crud-example-tutorial

到目前为止,一切都对我来说很好(插入和删除)。现在,我希望该单一表单不仅用于将数据插入数据库,而且还用于编辑,只是不需要在 html 文本字段中手动输入 id 字段,如示例中所示。 另外,我想在没有像 edit/id 这样的 seo 路径的情况下执行此操作(我希望它像 edit?id=1)

我在我的问题中发布的第二个链接中看到,为此定义了控制器类 - PersonController.java(该示例使用 Spring MVC,我正在使用 JSF,如第一个链接教程所示,但是我想我需要那个控制器)

在那里定义:

@RequestMapping("/edit/{id}")
    public String editPerson(@PathVariable("id") int id, Model model){
        model.addAttribute("person", this.personService.getPersonById(id));
        model.addAttribute("listPersons", this.personService.listPersons());
        return "person";
    }

但我没有在 .java 文件或 .jsf/.xhtml 文件中看到调用该方法 editPerson 的地方?我知道我应该用这样的请求映射来写它:

@RequestMapping(value = "/index.xhtml", method = RequestMethod.GET, params = { "id" })

我用那个 RequestMapping 写了同样的方法,但现在该怎么办? 当 url 中存在名为“id”的 GET 参数时,我必须在哪里调用该方法以使用数据填充我的插入表单?我想在存在名为 id 的 GET 参数时实现功能,然后将显示用数据填充的表单(对于数据库中的那个 id);保存填写好的表格后,更新将发生在数据库中,而不是插入。当 url 中没有 id 参数(GET 方法)时,应该进行插入。我希望我足够清楚。

谁能告诉我源代码怎么做?

【问题讨论】:

  • 我们是 Borg 我不使用 JSP,我使用 JSF(.xhtml 和 .jsf)文件。我认为你没有意识到我需要什么。我知道如何将我的参数发送到 url。我不知道,当 url 中存在 id 时,如何显示来自数据库的相应填充数据(而不是空白表单)?
  • 不知道您具体要问什么,因为这里没有任何意义,但这绝对是您阅读的食物:stackoverflow.com/questions/18744910/… 尽管如此,真正的 JSF 答案(不会混淆 Spring MVC 噪音)将是 @ 987654324@您接受哪些重复?

标签: java spring hibernate jsf aop


【解决方案1】:

试试这个代码:

    @RequestMapping(value = "/index.xhtml", method = RequestMethod.GET)
    public String editPerson(@RequestParam int id, Model model){
        model.addAttribute("person", this.personService.getPersonById(id));
        model.addAttribute("listPersons", this.personService.listPersons());
        return "person";
    }

【讨论】:

  • 我不必在代码中的任何地方调用editPerson()?你说它可以像这样定义而不是调用它;当我尝试保存它时它会更新我的表单吗?
  • “人”是局部视图还是完整的网页?我的意思是您会用此响应或整个页面替换部分视图吗?如果是整体,那么您可以在网络浏览器中打开“/index.html?id=1”或将其放入 html 链接中。
  • 我不需要用此响应替换部分视图。我需要你所说的:“那么你可以打开 /index.html?id=1” 只是为了确定.. spring/jsf/hibernate 如何知道必须调用 editPerson 方法来填充 RequestMapping 参数?我不明白.. 如果这是正确的,我可以写任何东西而不是 editPerson?
  • ? 符号之后的参数称为请求参数。在我们的例子中 ?id=1 我们有 id 请求参数,Spring 将解析它并使用值 1 填充您方法的 id 参数。最好将 url "/index.xhtml" 重命名为 "/editPerson.xhtml",Spring 将完全使用此特定方法。
  • 查看Spring docs 了解它的工作原理。
猜你喜欢
  • 2016-06-23
  • 1970-01-01
  • 2017-03-04
  • 2021-01-29
  • 1970-01-01
  • 2018-12-12
  • 2019-10-07
  • 2011-02-13
  • 2015-08-26
相关资源
最近更新 更多