File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes JSP and the fly likes How to run a method in JSP Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » JSP
Bookmark "How to run a method in JSP" Watch "How to run a method in JSP" New topic

How to run a method in JSP

Fritz Largosa
Ranch Hand

Joined: Sep 12, 2005
Posts: 70
I have a botton below named Button1 and a JSP method named method1. I want to be to execute method1 whenever someone clicks on Button1, but I do not know how. If there is a way this can be done please let me know. Any help is greatly appreciated. Thanks...


<form name="form3" method="post" action="">
<input type="submit" name="Button1" value="Submit">

public void method1(){...}
Ben Souther

Joined: Dec 11, 2004
Posts: 13410

In the first request getParameter("Button1") returns null so the code in the "if" block is ingored.

When you click on the button, the form is submitted back to the server.
This time getParameter("Button1") will return "Submit".
Since the return value is not null, the code in the "if" block is executed.

NOTE: Putting the logic right in the JSP is called Model1 web programming and is highly discouraged these days. Once you get a grip on the whole request/response nature of web programming, you might want to look into model2 or the MVC architecture.

Java API J2EE API Servlet Spec JSP Spec How to ask a question... Simple Servlet Examples jsonf
Fritz Largosa
Ranch Hand

Joined: Sep 12, 2005
Posts: 70
Is there another way, which does not involve reloading the page, but directly runs the method?
Nathan Pruett

Joined: Oct 18, 2000
Posts: 4121

I think that you're getting confused about how web applications work...

The method is on the server. The button is on a web page on the client.

There's no way the button can call directly to the method without making a new request. The problem is, requests generate some kind of response, and most responses usually refresh the page.

You could use AJAX to make a "background" request to the server to invoke the method without refreshing the page.

Write once, run anywhere, because there's nowhere to hide! - /. A.C.
I agree. Here's the link:
subject: How to run a method in JSP
It's not a secret anymore!