By | August 1, 2015

Java Jsp Tutorial – call a Java method on button click event of JSP or html

My Java file is:

public class MyClass{

public void function1(){
 
 // some code

}
public void function2(){

 //some code

}
public void function3(){

 //some code

}

}

And in HTML or JSP page consider we have three buttons.



1. If we clicked on button1 then only function1 will call,
2. If we click on button2 then only function2 will execute and
3. If on button3 then only function3 and so on.

Explanation –

HTML Code.

<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>

JAVA Code

@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.function1();

 } else if (request.getParameter("button2") != null) {

 myClass.function2();

 } else if (request.getParameter("button3") != null) {

 myClass.function3();

 } else {

 // some code

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

 }}

 

Share this knowledge ! Join us on Facebook ! Now Whatsapp sharing is supportable ! TooDey Inc.

Leave a Reply

Your email address will not be published. Required fields are marked *