You need a servlet ( <-- click the link, it isn't included for decoration only).
To the point, provided that you're targeting a Servlet 3.0 container (Tomcat 7, Glassfish 3, etc), then just create this class:
@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
new MyClass().print();
}
}
And fix your JSP's <body>
as follows (provided that JSP file is placed in root of web content and not in a subfolder):
<form action="hello" method="post">
<input type="submit" name="myButton" value="button" />
</form>
That's it.
The servlet is via @WebServlet
registered to listen on an URL of /hello
, relative to context root. The HTML form is instructed to submit to exactly that URL, relative to the URL of the JSP page itself. The method="post"
will invoke the servlet's doPost()
method wherein you've all the freedom to write down the desired Java code.
If you want more finer grained control depending on the button pressed, then give the button an unique name.
<form action="hello" method="post">
<input type="submit" name="myButton1" value="button1" />
<input type="submit" name="myButton2" value="button2" />
<input type="submit" name="myButton3" value="button3" />
</form>
then you can just check the button pressed as follows in servlet's doPost()
method:
if (request.getParameter("myButton1") != null) {
// button1 is pressed.
}
else if (request.getParameter("myButton2") != null) {
// button2 is pressed.
}
else if (request.getParameter("myButton3") != null) {
// button3 is pressed.
}
A completely different alternative is to go for an existing MVC framework which abstracts all this boilerplate away in a high degree, such as JSF, Spring MVC, Struts2, etc.
With JSF, it would look like this (you only need to replace legacy JSP by its successor Facelets; how Facelets look like is explained in a bit sane JSF tutorial, again, click the "JSF" link in previous paragraph for details):
<h:form>
<h:commandButton value="button1" action="#{bean.button1}" />
<h:commandButton value="button2" action="#{bean.button2}" />
<h:commandButton value="button3" action="#{bean.button3}" />
</h:form>
with just this class without ugly if/elses:
@ManagedBean
@RequestScoped
public class Bean {
public void button1() {
System.out.println("button1 invoked");
}
public void button2() {
System.out.println("button2 invoked");
}
public void button3() {
System.out.println("button3 invoked");
}
}