我的Java文件是: public class MyClass { public void method1() { // some code } public void method2() { //some code } public void method3() { //some code }} 在我的JSP页面中,我有三个HTML按钮。 如果我点击button1,那么
public class MyClass { public void method1() { // some code } public void method2() { //some code } public void method3() { //some code } }
在我的JSP页面中,我有三个HTML按钮。
如果我点击button1,那么只有method1将被调用,如果我点击button2,那么只有method2将执行,如果button3,那么只有method3等等。
我该如何实现?
只需给单个按钮元素一个唯一的名称。当按下时,按钮的名称可作为请求参数,通常与输入元素一样。您只需要确保按钮输入的type =“submit”,如< input type =“submit”>和< button type =“submit”>而不是type =“button”,它只会渲染一个“死”按钮,仅用于onclick的东西和全部。
例如。
<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); } }
或者,使用< button type =“submit”>而不是< input type =“submit”>,那么你可以给他们所有相同的名字,而是一个唯一的值。 < button>的值不会被用作标签,您可以将自己指定为孩子。
例如。
<form action="${pageContext.request.contextPath}/myservlet" method="post"> <button type="submit" name="button" value="button1">Button 1</button> <button type="submit" name="button" value="button2">Button 2</button> <button type="submit" name="button" value="button3">Button 3</button> </form>
同
@WebServlet("/myservlet") public class MyServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { MyClass myClass = new MyClass(); String button = request.getParameter("button"); if ("button1".equals(button)) { myClass.method1(); } else if ("button2".equals(button)) { myClass.method2(); } else if ("button3".equals(button)) { myClass.method3(); } else { // ??? } request.getRequestDispatcher("/WEB-INF/some-result.jsp").forward(request, response); } }
也可以看看:
> Servlet returns “HTTP Status 404 The requested resource (/servlet) is not available”
> How do I pass current item to Java method by clicking a hyperlink or button in JSP page?