【问题标题】:Checking which submit button was clicked检查单击了哪个提交按钮
【发布时间】:2014-07-15 01:52:12
【问题描述】:

我正在开发一个使用 J2EE 和 Spring Roo 作为框架的 Web 应用程序。

我想创建一个带有两个提交按钮的表单:

  • 一个用于保存并继续
  • 另一个用于保存和完成

    <form action="mycontroller" method="post"> <input type="submit" value="Save and continue"/> <input type="submit" value="Save and finish"/> </form>

所以我可以选择将数据存储在数据库中并添加更多条目,或者存储数据并完成该过程。

如何检查在处理操作的控制器的方法中单击了哪个提交按钮?

public class MyController {
    void actionMethod(...) {
        // check which submit was clicked
    }
}

【问题讨论】:

标签: forms spring jakarta-ee model-view-controller spring-roo


【解决方案1】:

如果可以的话,要减少 if-else,并从 Spring 框架中受益来处理这些映射,请尝试以下解决方案 (如果您没有很多元参数要在表单中发送):

<form action="AddToCartListController" method="post">
    <input type="submit" value="Save and continue"/>
</form>

<form action="CommitCartListController" method="post">
    <input type="submit" value="Save and finish"/>
</form>

...

public class CartListController {
    void AddToCartListController(...) {
        // business code
    }
    void CommitCartListController(...) {
        // business code
    }
}

// ... or ...

public class AddToCartListController {
    void actionMethod(...) {
       // business code        
    }
}

public class CommitCartListController {
    void actionMethod(...) {
       // business code
    }
}

并在 Spring 配置中定义适当的映射。

【讨论】:

    【解决方案2】:

    您应该为两个按钮添加一个名称字段:

    <input type="submit" name="button" value="Save and continue"/>
    <input type="submit" name="button" value="Save and finish"/>
    

    一旦进入控制器,你可以通过这个名称字段恢复元素并检查它的值字段:

    String field = request.getParameter("button");
    
    if ("Save and continue".equals(button)){
        // Do stuff
    }
    else if ("Save and finish".equals(button)){
        // Do a different stuff
    }
    else {
        // None of them were pressed
    }
    

    或者您也可以为两个按钮使用不同的名称值:

    <input type="submit" name="button1" value="Save and continue"/>
    <input type="submit" name="button2" value="Save and finish"/>
    

    在您的控制器中:

    String button1 = request.getParameter("button1");
    String button2 = request.getParameter("button2");
    
    if (button1 != null){
        // Do stuff
    }
    else if (button2 != null){
        // Do a different stuff
    }
    else {
        // None of them were pressed
    }
    

    首选第二种解决方案,因为它不依赖于元素的值

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-01
    • 2013-10-03
    • 1970-01-01
    • 1970-01-01
    • 2010-10-18
    相关资源
    最近更新 更多