title: JSP - How to write a valid search form
body: <p>I have a problem with a search form in a JSP project. In particular an user can subscribe to an event and the admin must be able to search all the members of that event.</p>
  
  <p>I write a form like this:</p>
  
  <pre><code>out.println("&lt;fieldset&gt;&lt;legend&gt;Search&lt;/legend&gt;&lt;form action=\"cercaIscritti.jsp\" method=\"post\"&gt;"
              + "Name: &lt;input name=\"name\" type=\"text\"&gt;&lt;br&gt;Surname: &lt;input name=\"surname\" type=\"text\"&gt;&lt;br&gt;"
              + "Belonging: &lt;input name=\"belonging\" type=\"text\"&gt;&lt;br&gt;Countr: &lt;input name=\"country\" type=\"text\"&gt;&lt;br&gt;"
              + "&lt;input type=\"submit\" value=\"Cerca\"&gt;&lt;/fieldset&gt;&lt;/form&gt;");
  </code></pre>
  
  <p>(If it isn't readable: there are four <code>&lt;input&gt;</code>, one for each column in the table <code>user</code> and a <code>&lt;input&gt;</code> for submit).</p>
  
  <p>I would like all the fields to be optional so that the admin can fill what it wants, but how do I build the query?</p>
  
  <p>I tried something like this :</p>
  
  <pre><code>public ResultSet searchSubs(String name, String surname, String belonging, String country) {
      try {
          boolean n = false, s = false, b = false, c = false;
          String query = "SELECT * FROM user WHERE ";
          if (!isEmpty(name)) {
              query += "firstName = ?";
              n = true;
          }
          if (!isEmpty(surname)) {
              if (n) {
                  query += " AND lastName = ?";
              } else {
                  query += "lastName = ?";
              }
              s = true;
          }
          if (!isEmpty(belonging)) {
              if (n || s) {
                  query += " AND belonging = ?";
              } else {
                  query += "belonging = ?";
              }
              b = true;
          }//and go on
  </code></pre>
  
  <p>But how can I add the values with the <code>PreparedStatement</code>? Is this the correct way? If it's not, how can I do something like that?</p>
  
  <p>The booleans are there in the middle only for test, I thought I would use them in some way but I do not know how.</p>