1

Iam new to JSP and i can't seem to figure out how to run code only when the user clicks on the button..here's my code:

$

<form action="list_computers.jsp" method="post">                


        Search:
<input type="text" name="FromTextBox1"/>

<input type="submit" value="Search it!" >
   <%

        String TheSearch = (String)request.getParameter("FromTextBox1"); 

        String GetIt = Searcher(TheSearch);

        out.println(GetIt);

   %>
</form>

The Searcher() is a function i declared above this. Any help would be really appreciated.

Shahvez Irfan
  • 31
  • 1
  • 5
  • 1
    What this code does is calls the function Searcher() when the page loads, and consequently throws an exception. – Shahvez Irfan May 07 '12 at 21:07
  • 2
    [Please don't use scriptlets](http://stackoverflow.com/questions/3177733/how-to-avoid-java-code-in-jsp-files). – Matt Ball May 07 '12 at 21:10

2 Answers2

2

You need to do something like

if (request.getParameter("submit") != null) {
// do work here
}

You also need to give a name to your button

<input type="submit" value="Search it!" name="submit">

When user clicks (or presses enter), request['submit'] will be equal to "Search it!"

I highly recommend moving this logic to the top of the page or even better to a controller.

Amir Raminfar
  • 33,777
  • 7
  • 93
  • 123
0

you need to use javascript to check for the onclick event here's a little example with JQuery

 $("input[type='submit']").click(function(){
      //do your thing
      // use event.preventDefault(); to stop submission if need
 });
BenMorel
  • 34,448
  • 50
  • 182
  • 322
Hugo Alves
  • 1,555
  • 2
  • 18
  • 41
  • This has nothing to do with JavaScript. We are talking about jsp code. – Amir Raminfar May 07 '12 at 23:55
  • sry for the delayed response. My bad about the answer not being about jsp, miss understood the question. But isn't it better to separate the client side logic from view building and use javascript that way it's also easily reusable. – Hugo Alves May 10 '12 at 11:55
  • You do want to separate the logic always. Having the some code in js and some in HTML is not however separating anything. Look at the MVC model. You want to have a JSP page with all the HTML and a controller with all the logic. – Amir Raminfar May 10 '12 at 14:15