How do i call a method from a jsp when i click in a button?
I wrote this code,but dont work..
<%@page import="my.package.class.MyClass" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<input type="submit" name="myButton" value="button" onclick="callMethod()"/>
</body>
</html>
<%!
void callMethod(){
new MyClass().print();} %>
there is any way more easy? or this is the right way for to do?
ps: I dont want to use javascript
edit: My class just have a method “print”,that prints something like “test” in system.out.println
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:
And fix your JSP’s
<body>as follows (provided that JSP file is placed in root of web content and not in a subfolder):That’s it.
The servlet is via
@WebServletregistered 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. Themethod="post"will invoke the servlet’sdoPost()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.
then you can just check the button pressed as follows in servlet’s
doPost()method: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):
with just this class without ugly if/elses: