Multiple method calling using single servlet [dupl

2019-03-05 12:01发布

I am new to JavaEE and have a query regarding a servlet that has multiple methods.

I want to know how I can call a specific method on a servlet, when I click "Submit" button in JSP.?

Someone have suggested to use HTML hidden fields but I have no idea on how to implement them in Jsp.

4条回答
Root(大扎)
2楼-- · 2019-03-05 12:12

Hidden fields in a JSP are the same as in HTML:

<input type="hidden" name="name" value="value">

Then in your servlet you can do

if (request.getParameter("name").equals("value")) { /* do something */ }
查看更多
地球回转人心会变
3楼-- · 2019-03-05 12:19

i dont think having 3 buttons is the best solution,basis on the logic and parameters method asked,
i believe this can be an accurate solution-

On the basis of parameters passed ,we can have 2 methods to access different actions via javascript-
1)getting values from user,checking them in javascript.
2)getting values from user,checking them in javascript,assigning values to hidden variables accordingly,calling servlets and using those hidden values.i have elaborated method1.

    <html>
<head>
    <script type="text/javascript">
    function nawab() {
    param = document.getElementById('param1').value;
    alert('in nawab');
    if (param != "") {
    if (param === 'abc') {
          alert('abc');
          document.forms[0].action = "nawabServlet";
          document.forms[0].submit();
    }
    if (param === 'def') {
     alert('def');
     document.forms[0].action = "nawabServlet2";
     document.forms[0].submit();
     }          
}           
else{
      alert('empty');
      document.forms[0].action = "nawabServlet";
      document.forms[0].submit();
     }
 }
 </script>
 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
 <title>nawab has come</title>
 </head>
 <body>
  <form>
        param1:<input type="text" name="param1" id="param1"></select> 
        <input type="submit" onclick="nawab()">
   </form>
  </body>
</html>
查看更多
老娘就宠你
4楼-- · 2019-03-05 12:25

Depends on which method you want to call. Assuming that the URL Pattern declared for your servlet in web.xml is /myservlet*,

For doGet, just use a URL

http://localhost:8080/myservlet?name=value

For doPost, use a form.

<form action="/myservlet" method="post">
    <input type="text" value="value" name="name" />
</form>
查看更多
贼婆χ
5楼-- · 2019-03-05 12:26

You can just give the submit button a specific name.

<input type="submit" name="action1" value="Invoke action 1" />
<input type="submit" name="action2" value="Invoke action 2" />
<input type="submit" name="action3" value="Invoke action 3" />

The name-value pair of the pressed button is available as request parameter the usual way.

if (request.getParameter("action1") != null) {
    // Invoke action 1.
}
else if (request.getParameter("action2") != null) {
    // Invoke action 2.
}
else if (request.getParameter("action3") != null) {
    // Invoke action 3.
}
查看更多
登录 后发表回答