2

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

user1851366
  • 256
  • 6
  • 20
  • 41
  • 2
    It looks like you're learning about Java Web Applications. It would be good to start with [the JSP](http://stackoverflow.com/tags/jsp/info) and [the Servlets](http://stackoverflow.com/tags/servlets/info) SO wikis. – Luiggi Mendoza Jan 18 '13 at 14:45
  • Where you are creating a bean? – joey rohan Jan 18 '13 at 14:46
  • The bean should be MyClass myclass = new MyClass(), myclass.print(). But i think is the same that calling just new MyClass.print() – user1851366 Jan 18 '13 at 14:49
  • Please refer to the links I posted in my previous comment. Also, since you're still learning, you should do it in the right way, so stop using scriptlets at all. The explanation is very detailed here: [How to avoid Java Code in JSP-Files?](http://stackoverflow.com/questions/3177733/how-to-avoid-java-code-in-jsp-files). As a lesson, don't try to mix Java code with your JSPs, it's a bad practice. – Luiggi Mendoza Jan 18 '13 at 14:54
  • Java does not equal Javascript. Your `onclick` handler is looking for a Javascript function named `callMethod()`. The method you wrote in your JSP is Java, and is strictly a server-side entity (it won't appear in the client-side HTML page). Also, it is bad practice to put Java in JSPs. – GriffeyDog Jan 18 '13 at 15:03
  • So what is the best to way to call a java method? – user1851366 Jan 18 '13 at 15:07
  • Create a servlet. See the links provided by Luiggi. – BalusC Jan 18 '13 at 15:41
  • But how i call my servlet when click on button? is the same issue that im looking for.. – user1851366 Jan 18 '13 at 15:46
  • Check this out. http://stackoverflow.com/questions/5776731/invoke-bean-method-from-jsp – rikket Jan 18 '13 at 15:46
  • See the links provided by Luiggi. It clearly shows that `
    ` URL must point to servlet's URL.
    – BalusC Jan 18 '13 at 16:09

3 Answers3

5

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");
    }

}
Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
0

why not use servlets and MVC pattern, you have no need to write java methods within JSP.

Noah Martin
  • 1,708
  • 9
  • 35
  • 73
0

You are confusing where the bits of code involved in a JSP and the resulting HTML, which the browser displays, are running.

The bean that is accessible inside the JSP is in the servlet container (on the server) at the time the HTTP request is being processed and the HTML is generated from the JSP, while the button that fires the onclick event is inside the clients browser - therefore the button cannot invoke the bean directly.

In order to invoke server-side logic when the button is clicked you need to make an AJAX call back to the server (unless you're going to refresh the whole page, which is a bit crap).

Nick Holt
  • 33,455
  • 4
  • 52
  • 58