如何在 JSP 中特定按钮的单击/提交事件上调用特定的 Java 方法? [英] How do I call a specific Java method on a click/submit event of a specific button in JSP?

查看:22
本文介绍了如何在 JSP 中特定按钮的单击/提交事件上调用特定的 Java 方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 Java 文件是:

My Java file is:

public class MyClass {

    public void method1() {    
        // some code
    }

    public void method2() {
        //some code
    }

    public void method3() {
        //some code
    }
}

在我的 JSP 页面中,我有三个 HTML 按钮.

In my JSP page I have three HTML buttons.

如果我点击button1,那么只会调用method1,如果我点击button2,那么只会调用method2code> 将执行,如果 button3,则只有 method3,依此类推.

If I click on button1, then only method1 will be called, if I click on button2 then only method2 will execute, and if button3, then only method3, and so on.

我怎样才能做到这一点?

How can I achieve this?

推荐答案

只需给各个按钮元素一个唯一的名称即可.按下时,按钮的名称可用作请求参数,就像输入元素一样.

Just give the individual button elements a unique name. When pressed, the button's name is available as a request parameter the usual way like as with input elements.

您只需要确保按钮输入具有 type="submit"<input type="submit"><button type="submit">not type="button",它只为 onclick<渲染一个死"按钮/code> 东西和所有.

You only need to make sure that the button inputs have type="submit" as in <input type="submit"> and <button type="submit"> and not type="button", which only renders a "dead" button purely for onclick stuff and all.

例如

<form action="${pageContext.request.contextPath}/myservlet" method="post">
    <input type="submit" name="button1" value="Button 1" />
    <input type="submit" name="button2" value="Button 2" />
    <input type="submit" name="button3" value="Button 3" />
</form>

@WebServlet("/myservlet")
public class MyServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        MyClass myClass = new MyClass();

        if (request.getParameter("button1") != null) {
            myClass.method1();
        } else if (request.getParameter("button2") != null) {
            myClass.method2();
        } else if (request.getParameter("button3") != null) {
            myClass.method3();
        } else {
            // ???
        }

        request.getRequestDispatcher("/WEB-INF/some-result.jsp").forward(request, response);
    }

}

或者,使用

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆