David Castro wrote:
> I am creating a JSP application that generates a custom SQL query, based on the
> columns and rows that the user wants to see. As such, I have a whole bunch of
> repeated code in the page:
>
> Vector email = (Vector)session.getAttribute("rep_email");
> if (email != null) {
>   if (email.size() > 0) {
>     if (!firstClause) {
>       query += " AND ";
>       firstClause = false;
>     }
>     query += "(email = '" + email.elementAt(0) + "'";
>     for (int i=1; i<email.size(); i++) {
>       query += " OR email = '" + email.elementAt(i) + "'";
>     }
>     query += ") ";
>   }
> }
>
> This code is repeated for every clause added to the WHERE part of the query. I
> realize that I could extract this code into a JavaBean or other servlet, and
> call that, but I'd like to keep the code within the page, to make debugging
> faster (and maybe move it to an external .class file later). Is there a way
> with JSP to create a function within the page, which I could call for each
> column?

If you promise to move the code to a servlet/bean/action later, I tell
you how ;-) You can use a JSP declaration to declare a method:

   <%!
     private String createColumnClause(String column, String value) {
       ...
       return clause;
     }
   %>

Note that the method has access to only instance variables (which should
be avoided for thread-safety reasons) so you have to pass it all data
it need as parameters.

You can then call it from a scriptlet:

   <%
     String clause = createColumnClause("email", email);
   %>

Hope this helps,
Hans
--
Hans Bergsten           [EMAIL PROTECTED]
Gefion Software         http://www.gefionsoftware.com
JavaServer Pages        http://TheJSPBook.com

===========================================================================
To unsubscribe: mailto [EMAIL PROTECTED] with body: "signoff JSP-INTEREST".
For digest: mailto [EMAIL PROTECTED] with body: "set JSP-INTEREST DIGEST".
Some relevant FAQs on JSP/Servlets can be found at:

 http://archives.java.sun.com/jsp-interest.html
 http://java.sun.com/products/jsp/faq.html
 http://www.esperanto.org.nz/jsp/jspfaq.jsp
 http://www.jguru.com/faq/index.jsp
 http://www.jspinsider.com

Reply via email to