【问题标题】:Spring MVC Passing object from a foreach to another ControllerSpring MVC将对象从foreach传递到另一个Controller
【发布时间】:2018-02-01 03:38:28
【问题描述】:

我有一个由forEach 弹簧标签显示的对象列表。这是jsp的代码:

<c:forEach items="${liste_fiche}" var="fiche">
                <div class="card blue-grey darken-1">
                    <form:form action="display_fiche" method="post" commandName="fiche" varStatus="status">
                        <div class="card-content white-text">
                            <span class="card-title">Fiche numéro ${fiche.id}</span>
                        <p>reference de la fiche : ${fiche.ref_fiche}</p>
                        <p>type de fiche : ${fiche.typeFiche}</p>
                        </div>
                        <div class="card-action">

                            <button type="submit" action="display_fiche"
                                class="waves-effect waves-light btn">Afficher la fiche</button>

                        </div>
                    </form:form>
                </div>
    </c:forEach>

上面的代码有以下结果:

当我点击“Afficher la fiche”时,我想在另一个控制器上选择实际的 fiche 对象。

我尝试通过以下控制器进行操作:

@RequestMapping(value="display_fiche", method = RequestMethod.POST)
private ModelAndView displayFiche(@ModelAttribute("fiche") Fiche fiche, ModelMap modelMap) {
    System.out.println("Fiche séléctionnée : " + fiche.getId());
    return model;
}

我不知道这是否是好方法,因为它不起作用。我总是得到一个“0”到fiche.getId()。如果不可能,我怎么能只传递fiche.id 元素?

【问题讨论】:

    标签: spring jsp spring-mvc spring-annotations


    【解决方案1】:
    <button type="submit" action="display_fiche" class="waves-effect waves-light btn">
    Afficher la fiche
    </button>
    

    创建一个隐藏的输入来保持被点击的id。

    在上面的按钮中添加一个 JavaScipt 调用,在实际提交表单之前将点击的 id 存储到隐藏的输入中。

    但您似乎不需要formpost 这样复杂的方法。使用通常的&lt;a&gt; 标签就足够了,并在控制器端进行了映射。此外,仅传递 fiche id 就足够了。

    <a href="/display_fiche/${fiche.id}" class="waves-effect waves-light btn">
    Afficher la fiche
    </a>
    

    和控制器

    @RequestMapping(value="/display_fiche/{id}", method = RequestMethod.GET)
    private ModelAndView displayFiche(@PathVariable("id") Long id, ModelMap modelMap) {
        System.out.println("Fiche séléctionnée : " + id);
        return model;
    }
    

    【讨论】:

    • 感谢您的回答,我想我会使用您的第二个解决方案。事实上,带有href 的 GET 请求似乎对我有好处 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-10
    • 2016-09-06
    相关资源
    最近更新 更多