1

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.

sohel khalifa
  • 5,602
  • 3
  • 34
  • 46

4 Answers4

5

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.
}
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
2

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 */ }
Skip Head
  • 7,580
  • 1
  • 30
  • 34
1

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>
adarshr
  • 61,315
  • 23
  • 138
  • 167
0

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>
bondkn
  • 420
  • 5
  • 11