SitePoint Sponsor

User Tag List

Results 1 to 7 of 7
  1. #1
    SitePoint Addict
    Join Date
    Jul 2006
    Posts
    200
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    convert to new expression language

    My application (at least part of it) is as follows:

    owners search form:
    Code:
    <html>
    
    <head>
    <meta http-equiv="Content-Language" content="en-us">
    <meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
    <title>Search string</title>
    </head>
    
    <body onload="document.schform.p11.focus();">
    
    <form name="schform" method="POST" action="owners.jsp">
      <blockquote>
        <blockquote>
          <p>Search string: <input type="text" name="p11" size="20">&nbsp;&nbsp;&nbsp;
          <input type="submit" value="Submit" name="B1">&nbsp;&nbsp;
          &nbsp;&nbsp;&nbsp;&nbsp; <input type="reset" value="Reset" name="B2"></p>
        </blockquote>
      </blockquote>
    </form>
    
    </body>
    
    </html>
    For example you can enter the letters wh to get only owners names that start with wh.

    owners.jsp page showing 5 records at a time with pagination:
    Code:
    <!-- <link rel="stylesheet" href="include/locked-column.css" type="text/css"> -->
    <link rel="stylesheet" href="include/style.css" type="text/css">  
    <!-- <script type="text/javascript" src="include/lock.js"></script> -->
    <script type="text/javascript">
    function cell(id)
    {
    var x=document.getElementById('myTable').rows[id].cells;
    // alert(myTable.rows[id].cells[1].firstChild.nodeValue);
    opener.document.petsedit.ownerid.value = myTable.rows[id].cells[0].firstChild.nodeValue;
    opener.document.petsedit.petowner.value = myTable.rows[id].cells[1].firstChild.nodeValue;
    opener.document.petsedit.ostreet.value = myTable.rows[id].cells[2].firstChild.nodeValue;
    self.close();
    }
        
    </script>
    
    <%@ page language="Java" import="java.sql.*" %>
    <%@ include file = "util.inc" %>
    <%@ include file = "include/pag.inc" %>
    <jsp:useBean id="ob" class="OwnerBean.ownerbean" />
    <jsp:setProperty
    name="ob"
    property="p11"
    value='<%= request.getParameter("p11") %>' />
    <%
    out.println("p11=" + ob.getp11());
    
    // String varp1 = request.getParameter("t11");
    String varp1 = ob.getp11();
    int varownerid;
    String OName;
    String p1;
    int p;
    int rkount = 0;
    int pages;
    ResultSet rc = null;
    ob.connect();
    rc = ob.exeSQL();
    int rowcount;
    rc.next();
    rowcount = rc.getInt(1);
    rkount = rowcount;
    rc.close();
    ob.close();
    out.println(rkount);
         pages = rkount;
    out.println("Count of Records : " + pages + "<br>");
    
    int cPage;
    cPage = (pages / 5);
    if (pages < 6)
        {
        cPage = 1;
        }
    else
        {
            if ((cPage * 5) == pages)
                {
                cPage = cPage;
                }
            else
                {
                cPage = (cPage) + 1;
                }
        }
    out.println("Count of Pages : " + cPage + "<br><p><p>");
    out.println("<hr>");
    int cpage;
    int currentRs;
    String pt;
    int varpt;
    pt = request.getParameter("mv");
    if (pt == null)
    {
    currentRs = 0;
    varpt = 1;
    out.println("varpt = " + varpt);
    }
    else
    {
    cpage = Integer.parseInt((String)pt);
    currentRs = 5 * (cpage - 1);
    out.println(cpage + "<br>");
    varpt = cpage;
    out.println("varpt = " + varpt);
    }
    ResultSet rs = null;
    ob.connect();
    String sql;
    sql = "SELECT ownerid, oname, ostreet FROM powners WHERE oname like ? ORDER BY oname LIMIT "+ currentRs +",5";
    rs = ob.execSQL(sql);
    out.println("<html>");
    out.println("<head>");
    out.println("</head>");
    out.println("<body>");
    out.println("<div id=tbl-container>");
    out.println("<table width=95% border=1 id='myTable' name='myTable'>");
    
    out.println("<thead>");
    out.println("<tr>");
    out.println("<th>OWNER ID</th>");
    out.println("<th>OWNER NAME</th>");
    out.println("<th>OSTREET</th>");
    out.println("<th>EDIT</th>");
    out.println("</tr>");
    out.println("</thead>");
    out.println("<tbody>");
    
    int kount = 0;
    String rowid;
    
    
    while (rs.next())
    {
    kount = kount + 1;
    rowid = "a" + Integer.toString(kount);
    varownerid = rs.getInt("ownerid");
    OName = rs.getString("oname");
    out.println("<tr id=" + rowid + " onMouseover=this.bgColor='lightgrey' onMouseout=this.bgColor='#FFFFFF' onclick='cell(this.id)'>");
    // out.println("<tr>");
    out.println("<td>" + varownerid + "</td>");
    out.println("<td>" + rs.getString(2) + "</td>");
    
    if (rs.getString(3) != null && rs.getString(3).length() > 0)
        {
        out.println("<td>" + rs.getString(3) + "</td>");
        }
    else
        {
        out.println("<td>" + "&nbsp;" + "</td>");
        }
    
    // '<td>'.'<a href="JavaScript:"onclick="">'.$rowid.'</a>'.'</td>'.
    
    out.println("<td><a href=\"JavaScript:\" onclick=\"\">" + rowid + "</a></td>");
    out.println("</tr>");
    }
    // out.println("</tr>");
    out.println("</tbody>");
    out.println("</table>");
    // out.println("</div>");
    
    out.println("<br>");
    out.println("<table width=95% >");
    out.println("<tr>");
    out.println("<td>");
    String queryvars = "p11=" + varp1;
    
    String vfile = "owners.jsp";
    String menu = pager(currentRs, cPage, varpt, varp1, vfile, queryvars);
    out.println(menu);
    // out.println("</div>");
    
    
    // deleted
    
    // deleted
    // *******************************************************************************
    
    String requri;
    
    String varqs = request.getQueryString();
    out.println(varqs);
    out.println("<br>");
    String varurl;
    if (varqs == null)
        {
        varurl = request.getRequestURL() +"?"+"mv="+varpt+"&p11="+varp1;
        }
    else
        {
        varurl = request.getRequestURL() +"?"+request.getQueryString();
        }
    
    out.println(varurl);
    out.println("<br>");
    out.println("<br>");
    session.setAttribute( "ownersess", varurl );
    out.println(session.getAttribute( "ownersess" ));
    out.println("<br>");
    
    out.println("</td>");
    out.println("</tr>");
    out.println("</table>");
    out.println("</div>");
    // out.println("<br>");
    out.println("</body>");
    out.println("</html>");
    rs.close();
    ob.close();
    %>
    <a href="ownersearch.htm">Back to search page</a>
    ownerBean.java:

    Code:
    package OwnerBean; 
    import java.io.*;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.sql.ResultSet;
    //import org.apache.jasper.tagplugins.jstl.core.Out;
    
    
    public class ownerbean {
    String obURL = "jdbc:mysql:///petback2";
    // String dbDriver = "COM.ibm.db2.jdbc.app.DB2Driver"; 
    // String upsql;
    private String p11;
    private int ownerid;
    private String oname;
    private String ostreet;
    private Connection obCon;
    
        /** Creates a new instance of ownerbean */
        public ownerbean() {
        super();   
        }
    public boolean connect() throws ClassNotFoundException,SQLException{ 
    Class.forName("com.mysql.jdbc.Driver");
    obCon = DriverManager.getConnection(obURL, "xxxxxxx", "xxxxxxxx"); 
    return true; 
    } 
    public void setownerid(int ownerid)
    {
    this.ownerid = ownerid;
    }
    
    public int getownerid()
    {
    return (this.ownerid);
    }
    
    public void setp11(String p11)
    {
    this.p11 = p11;
    // this.message = message;
    }
    
    public String getp11()
    {
    return (this.p11);
    }
    public void setoname(String oname)
    {
    this.oname = oname;
    }
    
    public String getoname()
    {
    return (this.oname);
    }
    
    public void setostreet(String ostreet)
    {
    this.ostreet = ostreet;
    }
    
    public String getostreet()
    {
    return (this.ostreet);
    }    
    public ResultSet exeSQL() throws SQLException{ 
    String sql = "SELECT count(ownerid) FROM powners WHERE oname like ?";
    try
      {
        PreparedStatement os  = obCon.prepareStatement(sql);
        os.setString(1, this.p11 + "%");
        ResultSet ownerr = os.executeQuery();
       // r.close();
        // s.close ();
        return (ownerr == null) ? null : ownerr;   
        
    }
      catch (SQLException se)
      {
        // log exception;
        throw se;
      }
    
    }    
    public ResultSet execSQL(String sql) throws SQLException{ 
    try
    {
    PreparedStatement os  = obCon.prepareStatement(sql);
    os.setString(1, this.p11 + "%");
    ResultSet ownerr = os.executeQuery();
    
    return (ownerr == null) ? null : ownerr;   
    // PreparedStatement s = null;
    
    
    }
      catch (SQLException se)
      {
        // log exception;
        throw se;
      }
    
    } 
    public void close() throws SQLException{ 
    obCon.close();     
    }    
     }
    util.inc which escapes strings if needed:

    Code:
    <%@page contentType="text/html"%>
    <%@page pageEncoding="UTF-8"%>
    <%!
    String convJS(Object s) {
    // Convert problem characters to JavaScript Escaped values
      if (s == null) {
        return "";
      }
      
      String t = (String)s;
      t = replace(t,"\\","\\\\"); // replace backslash with \\
      t = replace(t,"'","\\\'");  // replace an single quote with \'
      t = replace(t,"\"","\\\""); // replace a double quote with \"
      t = replace(t,"\r","\\r"); // replace CR with \r;
      t = replace(t,"\n","\\n"); // replace LF with \n;
    
      return t;
    } 
    %>
    <%!
    String replace(String s, String one, String another) {
    // In a string replace one substring with another
      if (s.equals("")) return "";
      String res = "";
      int i = s.indexOf(one,0);
      int lastpos = 0;
      while (i != -1) {
        res += s.substring(lastpos,i) + another;
        lastpos = i + one.length();
        i = s.indexOf(one,lastpos);
      }
      res += s.substring(lastpos);  // the rest
      return res;  
    }
    %>
    paging function:
    Code:
    <%@page contentType="text/html"%>
    <%@page pageEncoding="UTF-8"%>
    <%!
    String pager(int currentRs, int cPage, int varpt, String vart1, String vfile, String queryvars)
    {
    
    int p;
    String menu;
    menu = " ";
    
    if (cPage > 5)
    {
    String next = " >> ";
    String prev = " << ";        
    int varnext = varpt + 1;
    int varprev;
    if (currentRs > 0)
        {
        varprev = varpt - 1;
        menu = menu + "    " +"<a href=" + vfile + "?mv=" + varprev + "&" + queryvars + ">" + prev + "</a>";
        }
    int cpagestart;
    int cpageend;
    if (currentRs == 0)
        {
        cpagestart = 1;
        cpageend = 5;
        }
    else
        {
        // cpagestart = varpt + 1;
        cpagestart = varpt;
        cpageend = varpt + 4;
        }
            if (cpageend < cPage)
                {
                    for(p = cpagestart; p <= cpageend ; p++)
                    {
                        if (p == varpt)
                            {   
                            menu = menu + "    " +"<class=\"selected\">"+p;
                            }
                        else
                            {
                            menu = menu + "    " +"<a href=" + vfile + "?mv=" + p + "&" + queryvars + ">" + p +"</a>";
                            }
                     }
                }
            else
                {
                    for(p = cpagestart; p <= cPage ; p++)
                    {
                        if (p == varpt)
                            {   
                            menu = menu + "    " +"<class=\"selected\">"+p;
                            }
                        else
                            {
                            menu = menu + "    " +"<a href=" + vfile + "?mv=" + p + "&" + queryvars + ">" + p +"</a>";
                            }
                     }
                }
        if (varnext <= cPage)
            {
            menu = menu + "    " +"<a href=" + vfile + "?mv=" + varnext + "&" + queryvars + ">" + next + "</a>";
            }
    menu = menu + "    " +"&nbsp;&nbsp;&nbsp;&nbsp;Page " + varpt;
    }
    else
    {
    String next = " >> ";
    String prev = " << ";        
    int varnext = varpt + 1;
    int varprev;
    if (varnext >= 3)
        {
        varprev = varpt - 1;
        menu = menu + "    " +"<a href=" + vfile + "?mv=" + varprev + "&" + queryvars + ">" + prev + "</a>";
        }
        for(p = 1; p <= cPage ; p++)
        {
            if (p == varpt)
               {
                  menu = menu + "    " +"<class=\"selected\">"+p;
               }
            else
               {
                    menu = menu + "    " +"<a href=" + vfile + "?mv=" + p + "&" + queryvars + ">" + p +"</a>";
               }
       }
    if (varnext <= cPage)
        {
        menu = menu + "    " +"<a href=" + vfile + "?mv=" + varnext + "&" + queryvars + ">" + next + "</a>";
        }
        menu = menu + "    " +"&nbsp;&nbsp;&nbsp;&nbsp;Page " + varpt;
    
    }
    menu = menu +  " of " + cPage;
    
    
    
    return menu;
    } 
    %>
    Take these lines of code as an example, how would I convert to the new expression language?

    Code:
    if (rs.getString(3) != null && rs.getString(3).length() > 0)
        {
        out.println("<td>" + rs.getString(3) + "</td>");
        }
    else
        {
        out.println("<td>" + "&nbsp;" + "</td>");
        }
    Of course I'd like to convert all thats enclosed in <% %> tags to the new expression language.

    Can someone help me with some lines of code to convert?

  2. #2
    SitePoint Wizard
    Join Date
    Apr 2007
    Posts
    1,399
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    jim9, please don't be offended by my comments. This is a classic case of spaghetti code that no one will touch w/ 20 ft pole. JSP wasn't meant to be used like this. I wish the topic would change from "Java and JSP" to "Servlets and JSP". So many people thinks JSP is another PHP w/ different syntax. It's not! If you shown me this code face to face, I would permanently delete it from your hard drive. Anyways, you simply didn't know so it's not your fault. So, please take a look at this site.

    http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/

    If you have any questions then, I will gladly answer them for you. I'm sure other members will jump in too.

  3. #3
    SitePoint Addict
    Join Date
    Jul 2006
    Posts
    200
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    This is direct from the site you gave:
    Code:
    <!DOCTYPE >
    <HTML>
    <HEAD>
    <TITLE>Reading Three Request Parameters</TITLE>
    <LINK REL=STYLESHEET
    HREF="JSP-Styles.css"
    TYPE="text/css">
    </HEAD>
    <BODY>
    <H1>Reading Three Request Parameters</H1>
    <UL>
    <LI><B>param1</B>:
    <%= request.getParameter("param1") %>
    <LI><B>param2</B>:
    <%= request.getParameter("param2") %>
    <LI><B>param3</B>:
    <%= request.getParameter("param3") %>
    </UL>
    17 </BODY></HTML>
    Their jsp portion still shows the <%---%> tags

    What I meant is to convert to the new way like
    Code:
    <c:forEach var="row" items="${articles.allArticles}" />
    I don't understand what has to be in <%---%> tags, and what part can go in ${} tags.
    From what I read so far on sun site, the ${} are only to get things,data, whatever from a bean. Is this true?

  4. #4
    SitePoint Wizard rozner's Avatar
    Join Date
    Oct 2002
    Location
    Paris
    Posts
    1,058
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Basically most of what's inside <&#37; %> shouldn't be in the JSP. It should be in a servlet or some other Java class if you use a framework (like JSF or Struts).

    JSP 101 ... When a JSP is accessed it gets converted into a Java class which is then compiled and executed by the server. The generated class has a method called "service". This is what gets executed.

    So all the text in your JSP page gets converted into:

    JSP
    Code:
    <html>
      <h1>My Page</h1>
    </html>
    Java
    Code:
    out.println("<html><h1>My Page</h1></html>");
    Whatever is inside <% %> will just get inserted as is into the service method.

    JSP tags like <c:foreach /> also get converted into regular Java code although it's more than just print statements. A JSP tag is bound to a class which has some standard methods like "doStartTag" and "doEndTag". There are some others but those two are generally where most of the work gets done. I won't get into the details actually since I'll end up writing a whole tutorial, but when you use such tags in the page, they'll get converted to call the doStartTag and doEndTag at the appropriate locations.

    The code from your last post shows some simple examples of getting a request parameter using <% %>. I assume later they show you how to do so using tags. But generally you don't want to do anything complicated (like accessing the database) in a JSP page. You have a servlet to do that, which should in the end generate a Java bean (or a list of them) which you can then just display in the JSP page. The JSP should really be focused on presenting the data, not accessing it.

    Anyway, I would strongly recommend reading up on Servlets as this will help you understand how JSPs actually work. It wouldn't hurt to read up on the MVC design patter either.

    Regarding the expression language, generally speaking it's used to access a property on a bean or check a boolean property on a bean (in the case of <c:if /> or other conditional tags.

  5. #5
    SitePoint Addict
    Join Date
    Jul 2006
    Posts
    200
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    If you noticed, in my original post, I am using a bean (class) to actually execute the sql statement and then presenting the table via JSP page as in:

    Code:
    public ResultSet execSQL(String sql) throws SQLException{ 
    try
    {
    PreparedStatement os  = obCon.prepareStatement(sql);
    os.setString(1, this.p11 + "&#37;");
    ResultSet ownerr = os.executeQuery();
    
    return (ownerr == null) ? null : ownerr;   
    // PreparedStatement s = null;
    
    
    }
      catch (SQLException se)
      {
        // log exception;
        throw se;
      }
    
    } 
    public void close() throws SQLException{ 
    obCon.close();     
    }    
     }
    It's just in the newer javaee 6 spec I see ${} instead of <% %>. I know how to write a servlet, and what a servlet is. I also know you can show the presentation right in a servlet. I am not confused on this. I am confused on how to use ${} style programming. Please don't argue with me here, It's Oracle/Sun that has these ${} style things all over JSP as well as JSF pages. It appears that this is the new preferred way of programming.

    The following code is direct from the Oracle site in the javaee 6 tutor, the JSF section:
    Code:
    <html xmlns="http://www.w3.org/1999/xhtml"
          xmlns:h="http://java.sun.com/jsf/html">
        <h:head>
            <title>Facelets Hello World</title>
        </h:head>
        <h:body>
            #{hello.world}
        </h:body>
    </html>
    See the #{hello.world}. I am more used to this
    Code:
    <%
    out.println("last name=" + db.getlname());
    %>
    If getting from a bean class.
    Or jsp
    Code:
    <%
    out.println("Hello World");
    %>
    Or in a servlet or a bean(which I mean a class)
    Code:
    System.out.println("Hello World");
    Are these ${} style of tags only used to access information from a class? In other words how would you simply add the numbers 5 + 4 using a jsp page but with the new expression language(el)?

    For example I would do
    Code:
    <%
    int myresult;
    myresult = 5 + 4;
    out.println("The answer is: " + myresult);
    %>
    Now forget all about servlets for a minute, because this would be easy in a servlet or a bean.
    Here is what I want to know:
    How would you do this exact same thing in a jsp or jsf page, simply add 5 + 4 and show the result on a web page? And without the <% %> tags and using the new (el)?
    I am just trying to learn how to present data, results, or whatever without <% %> tags.

    Are you trying to say that you do everything with beans and servlets using System.out.println();
    If this is the case I can do ererything just in a bean class and wouldn't ever need to write a servlet. But I am trying to go by the spec that Oracle/Sun has for the presentation layer.

    P.S.
    You said in your last post:
    The JSP should really be focused on presenting the data, not accessing it.
    This is exaclly what I need to see a short example of.
    How without <% %> tags?
    Last edited by jim9; Jun 29, 2010 at 08:55. Reason: spell and added line

  6. #6
    SitePoint Wizard rozner's Avatar
    Join Date
    Oct 2002
    Location
    Paris
    Posts
    1,058
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Sorry I didn't actually read your entire post, it's kind of long. I agree with you that you should use EL and avoid using <% %>. I'm sure Sun/Oracle is promoting EL use and not <% %> but a lot of examples on the web still use <% %> and JSP is often taught that way.

    Although I think you're still missing the point that you can use Servlets and JSPs together without resorting to <% %>. Generally your servlet will call the bean to do DB access and store that in a List, then you forward to request to a JSP page that loops through the list (with a c:forEach maybe).

    Also you keep referring to the EL and JSP tags as the same thing (which they're not). The tags are what you should be interested in. The EL is used within the tags to access beans. But like JSF for example is based on the FacesServlet, which will eventually call a JSF page.

    Anyway I'm not sure what you want with a simple arithmetic example but it can certainly be done with tags. I think this ought to do it.
    Code:
    // JSTL version
    <c:out value="${4+5}"/>
    
    // JSF version
    <h:outputText value="#{4+5}"/>

  7. #7
    SitePoint Addict
    Join Date
    Jul 2006
    Posts
    200
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks for reply


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •