SQL tags in jstl

how to write sql tags in jstl

http://java.sun.com/j2ee/1.4/docs/tutorial/doc/index.html
Chapter 14

Similar Messages

  • How to use sql tag of jstl for inserting data

    hello
    I want to insert the data in to oracle through jsp using standard sql tags of jstl please help me

    1) Go to www.google.com.
    2) Enter in that input field "jstl sql tag tutorial" (assuming you want to learn the JSTL SQL tag library).
    3) Hit that search button.
    4) Explore the results. One of them is http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JSTL7.html

  • JSTL sql tags with jndi datasource

              Im trying to use JSTL sql tags but get "no suitable driver" when trying to connect
              to a jndi datasource. the jakarta dbtags works fine but jstl does not
              

              I figured it out but I'll leave it up to BEA to tell everyone how to doit.
              "Fred Forester" <[email protected]> wrote:
              >
              >
              >Im trying to use JSTL sql tags but get "no suitable driver" when trying
              >to connect
              >to a jndi datasource. the jakarta dbtags works fine but jstl does not
              

  • SQL in JSP - do I use JAVA code in % ... % or SQL Tag Library ??

    I have a small web app that makes needs to make about 12 SQL queries in a JSP and am trying to figure out what is the best way to do this
    I had initially coded this using plain JAVA code in the JSP as follows :-
    <%
    Connection conn = null;
    Statement st = null;
    ResultSet rs = null;
    try {
    st = conn.createStatement();
    rs = st.executeQuery("select .........");
    %>
    But then I came across the SQL Tag Library in an article and wonder if this is more efficient code?
    If so does anyone have a pointer to a good intro to these tags as they look complicated (I only am doing queries on the SQL database, no inserts or updates)

    Sometimes you've gotta do what you've gotta do.
    My rule is "no scriptlets".
    If you MUST access a database from a JSP, the only right way to do it is to use JSTL <sql> tags.
    %

  • Could someone help me with sql tags?

    Good morning here in Brazil, rsrs!!
    Well, I can�t see why it is giving me this exception, the codes are below
    could you give me some explanation? Thanks!
    my conection class and getDetalhes method:
    package teste;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.HashMap;
    import java.util.Iterator;
    public class Data {
        PreparedStatement prepStmt;
        ResultSet rs;
        Connection con;
        Detalhes detalhes;
        int codigo;
        ArrayList list;
        public Data()throws Exception {       
            try {
                Class.forName("org.gjt.mm.mysql.Driver");
                con = DriverManager.getConnection("jdbc:mysql://127.0.0.1/loja?user=marcos&password=131283");            
            } catch (Exception ex) {
                throw new Exception(" Database not found!!" +
                    ex.getMessage());
        public void remove() {
            try {
                con.close();
            } catch (SQLException ex) {
                System.out.println(ex.getMessage());
        public void setCodigo(int codigo){
            this.codigo = codigo;
        public Detalhes getDetalhes(){               
            try {
                String selectStatement = "select * from livraria where codigo ?";           
                prepStmt = con.prepareStatement(selectStatement);
                prepStmt.setInt(1, codigo);
                rs = prepStmt.executeQuery();
                while(rs.next())
                     detalhes = new Detalhes(rs.getString("titulo"), rs.getString("autor"), rs.getDouble("preco"), rs.getInt("codigo"));          
                prepStmt.close();
            }catch(Exception e){           
                System.out.println(e.getMessage());
            }finally {
               // close prepared statements and result sets within finally blocks
               if (rs != null) {
                  try {
                     rs.close();
                  } catch (SQLException sqle) {
                      System.out.println(sqle.getMessage());
               if (prepStmt != null) {
                  try {
                       prepStmt.close();
                  } catch (SQLException sqle) {
                      System.out.println(sqle.getMessage());
            return detalhes;
        public ArrayList getList(){
            try {           
                list = new ArrayList();
                String selectStatement = "select * from livraria";
                PreparedStatement prepStmt = con.prepareStatement(selectStatement);
                ResultSet rs = prepStmt.executeQuery();
                while(rs.next()){
                     detalhes = new Detalhes(rs.getString(1), rs.getString(2), rs.getDouble(3), rs.getInt(4));          
                     list.add(detalhes);
                prepStmt.close();                       
            }catch(Exception e){
                System.out.println(e.getMessage());
            return list;
    }my inicial Context class
    package teste;
    import java.util.ArrayList;
    import javax.servlet.*;
    public final class ContextPage implements ServletContextListener {
        private ServletContext context = null;
        Data bookDB;
        public void contextInitialized(ServletContextEvent event) {
            context = event.getServletContext();
            try {           
                bookDB = new Data();          
                context.setAttribute("bookDB", bookDB);
            } catch (Exception ex) {
                System.out.println("Couldn't create bookstore database bean: " +
                    ex.getMessage());
        public void contextDestroyed(ServletContextEvent event) {
      /*      context = event.getServletContext();
            Data dados = (Data) context.getAttribute("bookDB");
            if (dados != null) {
                dados.remove();
            context.removeAttribute("bookDB");              
    }   my jsp page
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %>
    <p><b><h1>Resultado:</h1></b></p><br>
    <sql:setDataSource dataSource="teste.Data"/>
    <sql:query var="books" sql="select * from livraria">
    </sql:query>
    <c:forEach var="book" begin="0" items="${books.rows}">
        ${book.titulo}
      </c:forEach>and the excption it brings me:
    exception
    javax.servlet.ServletException: Unable to get connection, DataSource invalid: "java.sql.SQLException: No suitable driver"
         org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:830)
         org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:763)
         org.apache.jsp.Resposta_jsp._jspService(Resposta_jsp.java:86)
         org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:105)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:860)
         org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:336)
         org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:301)
         org.apache.jasper.servlet.JspServlet.service(JspServlet.java:251)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:860)
         sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
         sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
         java.lang.reflect.Method.invoke(Method.java:585)
         org.apache.catalina.security.SecurityUtil$1.run(SecurityUtil.java:249)
         java.security.AccessController.doPrivileged(Native Method)
         javax.security.auth.Subject.doAsPrivileged(Subject.java:517)
         org.apache.catalina.security.SecurityUtil.execute(SecurityUtil.java:282)
         org.apache.catalina.security.SecurityUtil.doAsPrivilege(SecurityUtil.java:165)
    root cause
    javax.servlet.jsp.JspException: Unable to get connection, DataSource invalid: "java.sql.SQLException: No suitable driver"
         org.apache.taglibs.standard.tag.common.sql.QueryTagSupport.getConnection(QueryTagSupport.java:276)
         org.apache.taglibs.standard.tag.common.sql.QueryTagSupport.doStartTag(QueryTagSupport.java:159)
         org.apache.jsp.Resposta_jsp._jspx_meth_sql_query_0(Resposta_jsp.java:121)
         org.apache.jsp.Resposta_jsp._jspService(Resposta_jsp.java:69)
         org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:105)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:860)
         org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:336)
         org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:301)
         org.apache.jasper.servlet.JspServlet.service(JspServlet.java:251)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:860)
         sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
         sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
         java.lang.reflect.Method.invoke(Method.java:585)
         org.apache.catalina.security.SecurityUtil$1.run(SecurityUtil.java:249)
         java.security.AccessController.doPrivileged(Native Method)
         javax.security.auth.Subject.doAsPrivileged(Subject.java:517)
         org.apache.catalina.security.SecurityUtil.execute(SecurityUtil.java:282)
         org.apache.catalina.security.SecurityUtil.doAsPrivilege(SecurityUtil.java:165)

    I take that back. The problem is that you are trying to use something as a DataSource that is NOT a DataSource.
    The docs for the sql:setDataSource tag says:
    "Data source. If specified as a string, it can either be a relative path to a JNDI resource, or a JDBC parameters string as defined in Section 10.1.1."
    You are setting it as if it were requiring a JavaBean, which is not the case.
    You want to either use a JavaBean to do all the SQL (good thing) or the sql tags (not a good thing).
    If I were using your teste.Data bean, my JSTL would look like this:
        <jsp:useBean id="data" class="teste.Data"/>
        <c:set var="bookList" value="${data.list}" />
        <c:forEach var="book" items="${bookList}">
            ${book.titulo}<br />
        </c:forEach>If I were to use the sql tags (don't) then they would look like:
        <sql:setDataSource driver="org.gjt.mm.mysql.Driver"
                           url="jdbc:mysql://127.0.0.1/loja"
                           user="marcos" password="131283" />
        <sql:query var="bookResults" sql="select * from livraria"/>
        <c:set var="bookResultArray" value="${bookResults.rows}"/>
        <c:forEach var="bookRow" items="${bookResultArray}">
            ${bookRow.titulo}<br />
        </c:forEach>Note that the values coming out of the sql query tag are rows in the database, not your Detahles class. So you have to access the values via the names of your columns in the database, not by the properties (get methods) in your class.

  • How to get thr number of rows of an SQL query in JSTL

    hi guys,
    can anyone please tell me how do i perform a function which finds out the particular rownumber of an sql query in JSTL.....
    the same code in jsp is:
    <% plateRSet.getRowNum() %>
    how do i do this given plateRset is the var for a given iteration
    thanks
    rahul

    make your result set scrollable...Not such a good idea. With Oracle, the JDBC driver will read and cache all the ResultSet in memory (with other DBMSs/drivers the behavior will probably be different, but you will still have some unnecessary overhead).
    You can do the caching yourself if you think it's worth it. If the piece of code you posted is why you need this for, then use a List or Vector and you won't need to know the size upfront.
    Alin,
    The jTDS Project.

  • Struts tags versus JSTL tags

    Hi all,
    I'm trying to determine the performance and code generation differences between Struts and JSTL tags. Currently I have a very large JSP which is part of a Struts based application and it's teethering on the edge of the 'code too large for method' issue.
    Would replacing Struts based tags with JSTL tags reduce the amount of code generated in a jspService method for a JSP? For example replacing
    logic:equal or logic:match with c:if test="..."
    I would appreciate anyone opinion on this.
    Thanks,
    Paul

    Thanks,
    We've already followed those guidelines. It's really more to do a decision by our functional design team who decided to combine the functionality of two pages into one, which is something we should have flagged initially.
    Now we are left with this task of attempting to optimise. It's not the
    perfect solution.
    There is heavy use of logic:equal/match tags throughout the JSP and my initial investigation is that a c:if test="..." seems to generate less
    lines of code because there are not as many attributes to set on the
    object.
    Would anyone agree with me on that?
    Thanks,
    Paul

  • .tld for JSP SQL tags extension

    Hi.
    I cannot use Oracle SQL tags extensions (sal:dbOpen, etc) without .tld definitions. I cannot find it anywhere.
    Any ideas?

    Andrij, What version of oc4j are you using ?
    can you please check the ojspdemos( it includes sql taglib samples)
    The tlds are also part of the ojspdemos.ear file.
    -Prasad

  • SQL tag not working

    This is killing me why this doesn't work. This is populating a SELECT. I have the exact same setup in another application. The only major difference is this use mysql, the one that works uses SQL Server 2000. Table name and columns are different too, but the point is the same thing; fill a SELECT with values.
    The query appears to return nothing. I get a select with just a comma (",") in it.
    <sql:setDataSource
         driver="com.mysql.jdbc.Driver"
         url="jdbc:mysql://localhost/FABL"
         user=""
         password="" />
    <sql:query var="result">
         SELECT ID, FIRSTNAME, LASTNAME FROM CUSTOMERS ORDER BY LASTNAME, FIRSTNAME
    </sql:query>
    <select size="10" name="custid" size="1">
      <c:forEach items="${result.rows}" var="row">
         <option value="${row.id}">${row.lastname}, ${row.firstname}</option>
      </c:forEach>
    </select>Thanks,
    Karl

    I am using JSP 2.0 so the <c:out> shouldn't be neededJSP 2.0 has nothing to do with it. It's JSTL 1.0 or 1.1 that matters. Which one are you using? (I use JSTL 1.0, hence the <c:out>)
    There is no error. It just populates my SELECT with a single comma.Sure? I'd still add an error page that would display an exception if I got one.
    Permissions shouldn't be a problem. I ripped the datasource URL, user, and password straight from a
    bean that works fine.All that's fine, but MySQL GRANTs permission on an IP address basis. If the server on which the servlet/JSP engine runs isn't in the GRANT tables it won't have access.
    But that wouldn't explain why you only get a comma. Frankly, I don't know based on what you've posted.
    I'd break the problem down further. I'd write an object that would do the database work on my behalf and exercise it on the command line to make sure that it worked.
    I'd move all that SQL code out of the JSP and onto the middle tier where it belongs. I'd have the Java Bean that I just wrote to do the database interactions on my behalf in a <jsp:useBean> tag and simply iterate through the list of returned values. That's what JSPs are really for: display, not server side things like database interactions.

  • How to pass 100+ tags in a single sql/tag query

    <b>In my current application I have to pass 180+ tags in a single query to retrieve data from iHistorian.
    I want to know how to pass more thatn 100 tags in a single SQL or TAG Query using OLEDB or UDC connectors.
    If anybody has done it in the past ,please share with me and also let me know how to do it</b>

    Currently you can only query a maximum of 128 tags, this is a hard limit and may be changed in future releases of xMII, but < 11.5 (im fairly sure 12 also) all have the limit of 128.
    As for iHistorian with the OLEDB UDS, you can write a query that would return over 128 queries becasue this is an input limitation on the UDSs. (PLEASE DON"T ASK US HOW TO WRITE iHistorian QUERIES... we aren't experts in iHistorian).
    Please note that though you can query over 128 tags, the performance may not be what you expect... This may take a very long time to return.
    Martin

  • Can we use logical Operator in C:When  tag of JSTL

    Hi,
    I am developing an application in JSTL.
    I am using c:when tag. I have question whether can we use Logical OR operator in JSTL.
    I have tried using the following Syntax: The two bean fields have the value DISABLED
    <c:set var="testval" value = "${bean.val}" />
    <c:set var="testvalue" value ="${bean.value}" />
    Ex: <c:when test="${testval eq 'DISABLED'} or ${testvalue eq 'DISABLED'}">
    Ex: <c:when test="${(testval eq 'DISABLED') or (testvalue eq 'DISABLED')}">
    Ex: <c:when test="${testval eq 'DISABLED' or testvalue eq 'DISABLED'}">
    retrieving both these values from bean.
    The following syntaxes did not work.
    Please give me some pointers to resolve the issue.
    Thanks,
    Ravi
    Edited by: user10977303 on Nov 17, 2010 9:05 AM
    Edited by: user10977303 on Nov 17, 2010 9:10 AM

    The entire expression including the 'or' has to be inside the ${}.
    What this has to do with error handling beats me.

  • HTML tags amidst JSTL

    I am trying to print a text in bold, using the following code:
    <logic:present name="letterGenerationForm" property="arlTemplateHeader" >
    <logic:iterate name="letterGenerationForm" property="arlTemplateHeader" id="headerValues" >
    <b><bean:write name="headerValues"/></b>
    </logic:iterate>
    </logic:present>As seen, i want the output to be in bold! however, the text prints also with the HTML bold tags. as eg, o/p is: <b>TEXT FROM BEAN:WRITE</b>
    Is there a workaround to format the text coming from bean:write?

    I am trying to print a text in bold, using the
    following code:
    <logic:present name="letterGenerationForm"
    property="arlTemplateHeader" >
    <logic:iterate name="letterGenerationForm"
    property="arlTemplateHeader" id="headerValues" >
    <b><bean:write name="headerValues"/></b>
    </logic:iterate>
    </logic:present>As seen, i want the output to be in bold! however,
    the text prints also with the HTML bold tags. as eg,
    o/p is: <b>TEXT FROM BEAN:WRITE</b>
    Is there a workaround to format the text coming from
    bean:write?A better way would be to use CSS for formatting.
    JSTL might be better.
    %

  • Why no c:while tag in JSTL? Alternatives?

    Hi there.
    I am a bit surprised there is no <c:while> tag in the JSTL. For example while outputting a list I want to be able to do this:
    <c:while test="${currLevel < level--}"></ul></c:while>
    But of course I can't.
    Can anyone tell me:
    1. How to do this in JSTL
    2. Why the JSTL designers in their infinite wisdom didn't implement a <c:while> tag

    Problem already solved, but I think that answer to question number 2, why while tag is not implemented, may be because you cannot deliver expressions to tag handlers as parameters. Parameters are always solved before they are delivered to handlers.
    For example, if you put some boolean expression to JSP tag parameter,
    <c:while test="${ a!=b }">
    expression "a!=b" is solved once and the value is sent to handler, so it will be infinity loop or nothing at all.
    How while loop may be implemented in JSP would be(for example) something like this.
    <do>
    <while test="${ a!=b }"/> <%-- no end tag --%>
    <content>
    do something...
    </content>
    </do>
    While-tag gets value from boolean expression and sets that value to parent do-tag, content-tag asks from parent do-tag is it allowed to evaluate it's content.
    Now expression "a!=b" gets evaluated in every iteration.
    Quick thoughts,
    and sorry for bad english.

  • JSP 2 sql tag

    I need help linking to my mySQL DB through the web.xml file.
    Currently I am using this code in each JSP:
    <sql:setDataSource var="myconn"
         url="jdbc:mysql://localhost/drinksDB"
         user="USERNAME"
         password="PASSWORD"
         driver="com.mysql.jdbc.Driver" />How can I add the reference into my web.xml file?
    I thought that it went like this, but it doesn't work:
    <context-param>
              <param-name>javax.servlet.jsp.jstl.sql.dataSource</param-name>
              <param-value>localhost:3306:drinksDB,com.mysql.jdbc.Driver,USERNAME,PASSWORD</param-value>
    </context-param>I also tried this:
    <context-param>
              <param-name>javax.servlet.jsp.jstl.sql.dataSource</param-name>
              <param-value>jdbc:mysql://localhost/drinksDB,com.mysql.jdbc.Driver,USERNAME,PASSWORD</param-value>
    </context-param>Thanks,
    Matt
    Message was edited by:
    MatthewWeiler

    Currently I am using this code in each JSP:
    <sql:setDataSource var="myconn"
    url="jdbc:mysql://localhost/drinksDB"
    user="USERNAME"
    password="PASSWORD"
    driver="com.mysql.jdbc.Driver" />No don't.
    define your datasource in a config file. For example, if you are using tomcat, see this:http://tomcat.apache.org/tomcat-5.0-doc/jndi-datasource-examples-howto.html
    what app server are you using ?

  • Name-value pairs in SQL Tag

    Hi all,
    The problem in my code shown bellow is in "AND ? LIKE ?"
    since the name parameter cannot be ? in the name-value pairs
    But I really need the "name" param can be choosen by me :(
    Please help!! thks :)
    <sql:query var="plates" dataSource="${applicationScope.aod}">
    SELECT DISTINCT id, filename, project
    FROM xxxx
    WHERE project = ?
    AND ? LIKE ?
    <sql:param value="${param.project}"/>
    <sql:param value="${param.which}"/>
    <sql:param value="%${param.what}%"/>
    </sql:query>
    Cheers,
    George

    You would have to do it like this I think:
    <sql:query var="plates" dataSource="${applicationScope.aod}">
    SELECT DISTINCT id, filename, project
    FROM xxxx
    WHERE project = ?
    AND <c:out value="${param.which}"/> LIKE ?
    <sql:param value="${param.project}"/>
    <sql:param value="%${param.what}%"/>
    </sql:query>You then have to count on the param "which" generating correct SQL.

Maybe you are looking for

  • Are you using C++ AMP? We'd very much like to hear about it!

    Hello ladies and gentlemen. I come to you cap in hand, with a gentle request: given that C++ AMP is no longer an infant, we (the team working on it) are curious about its uptake. To be more precise, we would appreciate hearing from the people that ar

  • Multiple contract creation in ECC from a single GOA

    Hi Experts, I am working on a solution regarding to GOA in SRM - Contract in ECC creation and i am wondering about the following scenario: Create 1 GOA in SRM 5.0 for a central/global purchasing organization and when the appropriate BADI going to tra

  • Create multiple pdf files from html pages

    I have 15 html pages that I need to convert (possibly several times a day) into pdf files, and I need to get the process as automated as possible. I own an Acrobat Pro 8 license. 1) is there a command line I can launch to do this automatically? 2) fa

  • Replacing DVD/CD Drive (Question)

    Hello!   I need to replace dvd/cd drive in the PowerMac G4 (AGP).      Looking to add DVD+RW/CD.  Can I purchase any DVD+RW/CD drive?   Most DVD+RW/CD box says Windows specs.  Thanks, Jamie

  • Any tools to validate performance of an OAF Page?

    Hi Team, Please can anyone suggest me the tools available to validate the performance of an OAF Page?? regards sridhar