3 回答

TA貢獻1828條經(jīng)驗 獲得超3個贊
只需給各個按鈕元素一個唯一的名稱即可。按下按鈕后,按鈕的名稱可用作請求參數(shù),就像輸入元素一樣。
您只需要確保按鈕輸入的type="submit"in <input type="submit">和<button type="submit">and not一樣 type="button",這僅呈現(xiàn)一個“死”按鈕,僅用于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);
}
}

TA貢獻1911條經(jīng)驗 獲得超7個贊
<form method="post" action="servletName">
<input type="submit" id="btn1" name="btn1"/>
<input type="submit" id="btn2" name="btn2"/>
</form>
在按下它時,請求將轉到servlet頁面上的servlet,檢查按下了哪個按鈕,然后相應地將所需的方法作為objectName.method調用

TA貢獻1816條經(jīng)驗 獲得超6個贊
如果您有web.xml,那么
HTML / JSP
<form action="${pageContext.request.contextPath}/myservlet" method="post">
<input type="submit" name="button1" value="Button 1" />
</form>
web.xml
<servlet>
<display-name>Servlet Name</display-name>
<servlet-name>myservlet</servlet-name>
<servlet-class>package.SomeController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>myservlet</servlet-name>
<url-pattern>/myservlet</url-pattern>
</servlet-mapping>
Java SomeController.java
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Write your code below");
}
添加回答
舉報