JSTL Math

I have two jstl variables(actually that contain time values), and want to subtracting them from eachother? but not to usre about the syntax
is this correct?
<c:set var="sendTime" value="${endSendTime - startSendTime}"/>

JSTL doesn't have a exponential operator.
In fact, neither does java. You use the Math.pow() method.
If you are using a JSP2.0 container (Tomcat 5) you could probably define a function tag to do this ie
${myfunc:power(i+1, -n)}
Good luck,
evnafets

Similar Messages

  • Access JSTL variable outside JSTL tags

    hi
    I have this jstl tag:
    <sql:query var="brands" dataSource="${ds}">
    select brand
    from carbrand
    </sql:query>
    i want to manipulate the brands.rowCount without using the <c:set var="count" value="${brands.rowCount}"/>
    how can I read the ${brands.rowCount} outside the JSTL
    Because I want to use the Math.round, which I think can be use in
    <% Math.round(brands.rowCount/3)%>
    But I think its not reading the right variable or value?

    The variable is put into one of the JSP scope objects. You will be able to access it by using the pageContext.findAttribute("brands") method.
    Note: You will have to know the object's type. So look up the API for the sql tag and see what it is.
    Note: You will have to use brands.getRowCount() not brands.rowCount.

  • JSTL Timestamp problem

    I want to subtract current Timestamp from other Timestamp which is from Database, but follwing error occured
    org.apache.jasper.JasperException: /jstl_online_user.jsp(18,2) The function Timestamp must be used with a prefix when a default namespace is not specified
         org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:39)
         org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:409)
         org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDispatcher.java:150)
         org.apache.jasper.compiler.Validator$1FVVisitor.visit(Validator.java:1229)
         org.apache.jasper.compiler.ELNode$Function.accept(ELNode.java:122)
         org.apache.jasper.compiler.ELNode$Nodes.visit(ELNode.java:193)
         org.apache.jasper.compiler.ELNode$Visitor.visit(ELNode.java:234)My code
    <%@ page import="java.sql.*,javax.sql.*,javax.naming.*"  isELIgnored ="false"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>
    <sql:query var="rs_online" dataSource="helpdeskJNDIRef">
      Select u.user_id,user_ip,user_timestamp,user_what_action,user_what_arg1,user_name,user_display_name from user u , whos_online w where u.user_id=w.user_id
    </sql:query>
    <html>
      <head>
        <title>DB Test</title>
      </head>
      <body>
        <h2>Results</h2>
         <c:out value="${1 + 2 + 3}" />
        <c:forEach var="row" items="${rs.rows}">
              Text Message: <c:out value="${i.user_name}"/><br>
              <c:set var="logged" value="${(new java.sql.Timestamp(new java.util.Date().getTime())).getTime() - row.user_timestamp}" scope="page" />
                <c:out value="${logged}" />
        </c:forEach>
      </body>
    </html>Edited by: sagar_birari on 7 Jun, 2008 12:02 PM

    EL is not a scripting language, just an Expression Language, so you can't create timestamps with it.
    You probably shouldn't be doing this logic in the JSP anyway. Try moving the logic to beans. The code might look something like this:
    <%@ page isELIgnored ="false"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <!-- Create a bean then controls getting the user(s) from the database -->
    <jsp:useBean id="userLog" class="login.UserLog" scope="request" scope="page">
      <!-- Use a public void setUserName(String) method to set the w.user_id. 
           This method may execute the SQL and store results
      -->
      <jsp:setProperty name="user" property="userName" value="w.user_id"/>
    </jsp:useBean>
    <!-- Get a List<User> of all the logged in users that match the name given previously.
         If the setUserName method didn't execute the SQL, then the method
         public List getAllUsers(void) method this line calls should.
    -->
    <c:set var="usersLoggedIn" value="${userLog.allUsers}" scope="page" />
    <html>
      <head>
        <title>DB Test</title>
      </head>
      <body>
        <h2>Results</h2>
         <c:out value="${1 + 2 + 3}" />
        <!-- Iterate over the List<User> of users.  Objects in the list are of another bean type (login.User) -->
        <c:forEach var="user" items="${usersLoggedIn}">
              <!-- Call login.User#public String getUserName(void) method -->
              Text Message: <c:out value="${user.userName}"/><br>
              <!-- Call login.User#public String getLoggedTime(void) method which takes the current timestamp
                   and subtracts the time the user logged in, and converts it back to a String for display
              -->
                <c:out value="${user.loggedTime}" />
        </c:forEach>
      </body>
    </html>Of course, you could try doing the timestamp math in a scriptlet <% ... %> and storing the value in the pageContext.

  • Tricky table formatting using jstl

    I have an array List of elements of size for example50. I need to retrieve the elements as shown above and print them as a two dimensional table as below:
    The steps involved as below:
    1. I need to check the size of array say Z
    2. Divide it by 10 (ceil Z/10) and find the number of columns needed
    3. Print the elemnts from the ${List} as follows:
    1stelement   11thelement    21stelement   31stelement    41stelement
    2ndelement   12thelement   22ndelement   32ndelement   42ndelement
    10thelement   20thelement   30thelement    40thelement    50thelement I tried few methods and I feel it as bit trick for me as a beginner. I would appreciate very much if someone could help me! Thanks.

    So the requirement is to split the list into 10 rows, and as many columns as are required?
    Here is some basic code:
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
    <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
    <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
    <%@ page import="java.util.*" %>
    <html>
    <body>
    <%
      int numToDo = 50;
      List listOfNumbers= new ArrayList();
      for(int i=0; i<numToDo; i++){
           listOfNumbers.add(Integer.valueOf(i));
      pageContext.setAttribute("List", listOfNumbers);
      int numCols = (int)Math.ceil(listOfNumbers.size() / 10.0);
      pageContext.setAttribute("numCols", new Integer(numCols));
    %>
    <table>    
           <c:forEach var="entry" items="${List}" varStatus="status">     
               <c:if test="${status.index % numCols== 0}">
               <tr>
             </c:if>          
                 <td>${entry}</td>         
             <c:if test="${status.index % numCols== (numAppsPerLine-1)}">
               </tr>  
             </c:if>          
           </c:forEach>
    </table>
    </body>
    </html>The issue is how to calculate how many columns correctly.
    JSTL/EL doesn't have rounding math operators available, so I did that bit in scriptlet code for a quick/dirty approach.
    Apart from that calculation, it is all standard JSTL/EL.
    Basically it just keeps track of the index (using the varStatus variable) and starts/ends a table row as necessary.
    Cheers,
    evnafets

  • Juggle between jstl and jsp!

    I have a list of items and whose size is obtained by jstl as follows:
    <c:set var="num" value="${fn:length(form.namesList)}"/>I have to find the number of blocks using jsp and I am trying as follows which is giving jspException.
    <%int numCols = (int)Math.ceil( num / 10.0);%>Can anyone tell me the problem over here?
    I need to use numCols to display my results using jstl as follows:
    <c:forEach var="y" begin="${1}" end="${numCols }">
    </c:forEach>Can juggle between jstl and jsp like this?

    This depends on the version of JSP you are using:
    If you are using JSP 2.0 (like Tomcat 5), make sure you have downloaded and installed JSTL 1.1 and set the web.xml up to use the Servlet 2.4 specs. Then the code you wrote should work.
    If you are using JSP 1.x (like Tomcat 4 and below), make sure you have JSTL 1.0. Then you can only use EL (the Expression Language used to translate ${...} expressions) inside JSTL.
    If you want to use EL inside your custome tags, look through the Apache Jakarta sight. Somewhere they have an ELExpression translator (a couple of classes actually - whose full names I forget). These classes will let you take the ${...} expressions in as strings, pass them through the translators and get the correct objects back out.
    Or you could go a simpler root:
    <mob:whatever object="test" name="newname" />
    then in your custom tag:
      MyType test = (MyType)pageContext.findAttribute(object);
      test.setName(name);

  • Help with math / calculations in RTF templates

    Greetings,
    I know that there are math capabilities in the templates... I've seen the code samples in the Core Components guide.
    What this doesn't tell you is WHERE these things would go in a template. And... that... is my question.
    We are just starting to use BIP in conjunction with JDE EnterpriseOne (8.12, tool set 8.97.12). For our first attempt we're creating our template over a new report.
    I have a template where I sum two different repeating values (through the normal BI Properties) and place these values in two separate cells in a table. I want to sum the two of these together for a "grand" total.
    I've seen the "examples" but they really aren't very helpful. The xsfo, etc. for doing addition is fine, but WHAT are the values to add and WHERE does the code go?
    If anyone has done something like this or has experience using the embedded code I would appreciate hearing from you.
    Thanks in advance

    I see what you are saying about the spaces... but it made no difference... still got the error.
    The XML file is too large and convoluted to be pasted here.
    With reqards to the following snippet:
    COLA = <?sum(current-group()/COLA)?>
    COLB = <?sum(current-group()/COLB)?>
    Summ== <?sum(current-group()/COLA) + sum(current-group()/COLB)?>
    Where does THIS code go?
    Here is the error detail:
    ConfFile: C:\Program Files\Oracle\BI Publisher\BI Publisher Desktop\Template Builder for Word\config\xdoconfig.xml
    Font Dir: C:\Program Files\Oracle\BI Publisher\BI Publisher Desktop\Template Builder for Word\fonts
    Run XDO Start
    Template: C:\Documents and Settings\jdenison\My Documents\BIP Templates\R5642001\R5642001_TEMPLsave.rtf
    RTFProcessor setLocale: en-us
    FOProcessor setData: C:\Documents and Settings\jdenison\My Documents\BIP Templates\R5642001\R5642001_RICE0001_D081029_T144059683.xml
    FOProcessor setLocale: en-us
    java.lang.reflect.InvocationTargetException
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
         at java.lang.reflect.Method.invoke(Unknown Source)
         at oracle.apps.xdo.common.xml.XSLT10gR1.invokeProcessXSL(Unknown Source)
         at oracle.apps.xdo.common.xml.XSLT10gR1.transform(Unknown Source)
         at oracle.apps.xdo.common.xml.XSLT10gR1.transform(Unknown Source)
         at oracle.apps.xdo.common.xml.XSLTWrapper.transform(Unknown Source)
         at oracle.apps.xdo.template.fo.util.FOUtility.generateFO(Unknown Source)
         at oracle.apps.xdo.template.fo.util.FOUtility.generateFO(Unknown Source)
         at oracle.apps.xdo.template.FOProcessor.createFO(Unknown Source)
         at oracle.apps.xdo.template.FOProcessor.generate(Unknown Source)
         at RTF2PDF.runRTFto(RTF2PDF.java:629)
         at RTF2PDF.runXDO(RTF2PDF.java:439)
         at RTF2PDF.main(RTF2PDF.java:289)
    Caused by: oracle.xdo.parser.v2.XPathException: Extension function error: Method not found 'sum'
         at oracle.xdo.parser.v2.XSLStylesheet.flushErrors(XSLStylesheet.java:1534)
         at oracle.xdo.parser.v2.XSLStylesheet.execute(XSLStylesheet.java:521)
         at oracle.xdo.parser.v2.XSLStylesheet.execute(XSLStylesheet.java:489)
         at oracle.xdo.parser.v2.XSLProcessor.processXSL(XSLProcessor.java:271)
         at oracle.xdo.parser.v2.XSLProcessor.processXSL(XSLProcessor.java:155)
         at oracle.xdo.parser.v2.XSLProcessor.processXSL(XSLProcessor.java:192)
         ... 15 more

  • If statement in jstl

    I am new to jstl and I wrote the code for editing the information and i want the visible checkbox is checked if in the database it is visible or not checked in the checkbox if it is invisible but not working help me guys
    <div>
    <span class="label">Visible:</span>
    <input type="checkbox" name="visible"
    <c:if test="${ad.visible}">value="checked" </c:if>>
    </div>

    http://www.w3schools.com/tags/tag_input.asp
      <input type="checkbox" name="visible"
        <c:if test="${ad.visible}">checked="checked" </c:if>>

  • Hw can i get arabic support in oracleAS using jstl: showing '?????' symbols

    Hello All,
    I am using OracleAS for portal deployment and portlets UI constructed by using jstl.
    i have used spring portlet jstl for the jsp pages.
    when i am trying to change the language, it is showing '?????' symbols.
    I have used correct unicode. i tested in pluto portal server. when i deployed in oracleAS,
    for english not a problem. for arabic it is showing as '????'.
    i have used this code to get arabic in pluto. same code i used. i am getting error.
    <c:set target="${pageContext.response}" property="characterEncoding" value="UTF-8" />
    <fmt:setLocale value="ar" />
    <fmt:requestEncoding value="UTF-8" />
    i know it is not setting charector encoding.
    i tried some other too like:
    <head>
    <META http-equiv="Content-Type" content="text/html;charset=UTF-8"/>
    </head>
    and
    <%@ page pageEncoding="UTF-8" %>
    No improvement. please help me out of this.
    how can i get arabic support in oracle AS by using jstl?
    Thanks,
    Arun

    Only Apple Account Security could help at this point. You can try calling Apple Support in Canada - you'll have to find one of the several ways, such as Skype, to call an 800 number from outside of the relevant country - and ask for Account Security and see if they can help. Or you can find a friend who speaks Chinese and ask them to help you talk to Apple Support in China. There are really no other options that I know of.
    Note, by the way, that these are user-to-user support forums. You aren't speaking with Apple when you post here.
    Regards.

  • Is there a logic:match equivalent for JSTL?

    In a search page I execute a query which returns an array of objects (All objects are of the same object type and are cast to Object[]) and each object has many attributes. I tried using <logic:iterate>, but I was never successful in having it display any results. I believe this had something to do with the entire array being passed via session scope instead of just one record and me not specifying it properly with <logic:iterate>. I was able to successfully use <c:forEach> and it worked right away. I stuck with using that because of its "just works" ability in addition to using a lot of other JSTL code. However, one of the attributes that is being printed out needs to be parsed and is of the form "Yxxx". <logic:match> covers this very nicely, but when I specify it in the below code it is not able to find my variable in any scope.
    <c:forEach var="myResults" items="${sessionScope.result}" varStatus="status">
        <logic:match parameter='${myResults}' property='pin' value='Y'>
            <c:out value="Preeti"/>
        </logic:match>
    </c:forEach>I have done several google searches, but I haven't found a JSTL equivalent for <logic:match>. If there is one could someone please tell me what it is? In addition, although <logic:match> is great I still need to print out a substring of that attribute. Could someone tell me how to do that? If this is not possible could someone please tell me if its possible to use <logic:iterate> with an array of objects like I was attempting to do initially so that I could use <logic:match> at least?
    Thanks to all of you for your time.

    Yes you can use the logic:iterate tag. I think you have to specify the type of the exposed variable though. I prefer the forEach loop.
    I think you are using the wrong attribute in the logic:match tag. You should be using the "name" attribute rather than "parameter"
    Parameter attribute refers you to a request parameter, and I pretty sure you don't want that.
    So given the collection of objects in the session attribute "result"
    This should loop through them all, and see if they start with the letter 'Y'
    <c:forEach var="myResults" items="${sessionScope.result}" varStatus="status">
        <logic:match name='myResults' property='pin' value='Y'>
            <c:out value="Preeti"/>
        </logic:match>
    </c:forEach>As for the latter bit, are you using a JSP2 container and JSTL1.1? It would appear so seeing as you are trying to use EL expressions in the logic:match tag.
    If so, you could make use of the JSTL function library:
    <c:forEach var="myResults" items="${sessionScope.result}" varStatus="status">
       <c:if test='${fn:startsWith(myResults.pin, "Y")}'>
          <c:out value="${fn:substring(myResults.pin, 1, -1)}"/>
        </c:if>
    </c:forEach>And I've just spotted a very cool function in there: substringAfter
    <c:forEach var="myResults" items="${sessionScope.result}" varStatus="status">
          <c:out value='${fn:substringAfter(myResults.pin, 'Y')}'/>
    </c:forEach>Cheers,
    evnafets

  • Accessing JSTL values from JSP

    I've run into a problem I'm not sure has a solution. Could be bad design on my part, or just a poor imagination. If this has been answered previously, please point me to the post.
    I am using some JSTL to do a SQL query and displaying the records in a select box:
    <sql:query var="aResults" sql="select * from TYPE_STATE_LIST where tslAllowable=1" />                           
    <c:forEach var="oRecord" items="${aResults.rows}">                               
      <option value="<c:out value="${oRecord.tslID}" />"><c:out value="${oRecord.tslFullName}" /></option>                                   
    </c:forEach>I want to be able to reset their selection to the value they entered when the form is refreshed, though. I'm trying to figure out how to grab the oRecord value from the JSTL and use it in a JSP IF statement:
    <% if( oRecord.tslID==request.getParameter("state") ) { %>
      <option selected value="<c:out value="${oRecord.tslID}" />"><c:out value="${oRecord.tslFullName}" /></option> 
    <% } else { %>
      <option value="<c:out value="${oRecord.tslID}" />"><c:out value="${oRecord.tslFullName}" /></option> 
    <% } %>I thought about using the JSTL <c:choose> tag instead, but then how would I access the previous value with request.getParameter()?
    Any suggestions?

    ${param.state}It's better if you place the sql query into a class rather than display it in the jsp, it's more flexible and programmable.

  • Calendar in JSTL

    Hi ,
    I am using JSTL in JSP and there is an If statement which says
    if (Calendar.get(Calendar.YEAR)!=2000){
    do some thing
    I need to know how to write that if condition in JSTL.
    J4v4Guru.

    j4v4guru wrote:
    Hi ,
    I am using JSTL in JSP and there is an If statement which says
    if (Calendar.get(Calendar.YEAR)!=2000){
    do some thing
    I need to know how to write that if condition in JSTL.
    J4v4Guru.no JSTL docs available to you? think about <c:if> tag.
    %

  • Jstl c:if test

    I have put a string in my request:
    pageContext.getRequest().setAttribute("photoAccountmanager", "SUCCESS");
    How can I retrieve the string in jstl? The next statement doesn't work:
    <c:if test="${request.photoAccountmanager == 'SUCCESS'}" >
    </c:if>

    The proper EL way of retrieving from a particular scope is to use the Scope's map (requestScope for requests, sessionScope for sessions, applicationScope for application).
    <c:if test="${requestScope.photoAccountmanager == \"SUCCESS\"}">
    Note, that as long as there is no fear of having a variable of the same name in a different scope, specifying the scope is not necessary:
    <c:if test="${photoAccountmanager == \"SUCCESS\"}">
    Also not the escaped double quotes rather than single quotes. Not positive this is necessary, but I think it is the correct way to do it.
    Finally, if trouble still persists, try using
    <c:if test="${requestScope.photoAccountmanager eq \"SUCCESS\"}">

  • Using HashMap's ContainsKey() in JSTL

    Can we use HashMap's containsKey() in JSTL <c:if > statement
    I tried with the sample
    <html:select property="Type" multiple = "true" size = "3">
    <option value='<c:out value="${key}"/>'
    <c:if test="${requestScope.test.containsKey(key)}">
    selected
    </c:if>     
    <c:out value="${value}"/></option>
    </html:select >
    When i executed the above code i encountered JSP Error
    Can any one please let me know the correct code

    You can't call java methods from JSTL. It uses the EL - not java.
    However there is a solution.
    You access maps using the square brackets [ ] notation.
    ie ${test[key]}
    is the same as test.get(key)
    try
    <c:if test="${ not empty test[key] }"/>
    However seeing as you are using the struts tags, doesn't that automatically take care of this for you? Why don't you use the struts tags for the options list as well as the select? Just a thought :-)
    Cheers,
    evnafets

  • Two if condition in JSTL

    can I use and in if statement in JSTL, I f I want to change the following code to JSTL , what should I do
    if (!(Tassistant.equals("on"))&&         (!TassistantStart.equals("dd/mm/yyyy"))&&         (!TassistantUntill.equals("dd/mm/yyyy")))
    do I have to use ? can I use and to connection then I don't need that much close </c:if>
    <c:if test="${found.tassistant!='on'}"> }<c:if test="${found.tassistant!='dd/mm/yyyy'}"> </c:if>               </c:if>
    Thnak you!

    You can just use the same operators in EL.
    And in the future, please choose forum carefully. Posting a very simple question at a wrong forum doesn't let you overcome as smart.

  • Need help with Math functions for text-based calculator!!!

    I have the calculator working but I am having trouble figuring out thow to do a square root function, nth factorial, absolute value, and Fibonacci. Basically i got the easy part done. Also I am using the case to do the funtions but I am not sure if there are symbols on the keyboard that are commonly used for these funtions so i just made some up. I am new to java and this is only my second assignment so any help would be appreciated. Thanks
    import java.util.*;
    import java.math.*;
    public class calculator
    static Scanner console=new Scanner(System.in);
    public static void main(String[]args)
    double num1=0,num2=0;
    double result=0;
    char expression;
    char operation;
    String Soperation;
    System.out.println("Enter ? for help or enter the operation in which to be processed");
    Soperation=console.next();
    operation = Soperation.charAt(0);
    switch(operation)
    case '+':
    System.out.println("Please the first number");
    num1=console.nextInt();
    System.out.println("Please enter the second number");
    num2=console.nextInt();
    result=num1+num2;
    break;
    case'-':
    System.out.println("Please the first number");
    num1=console.nextInt();
    System.out.println("Please enter the second number");
    num2=console.nextInt();
    result=num1-num2;
    break;
    case'*':
    System.out.println("Please the first number");
    num1=console.nextInt();
    System.out.println("Please enter the second number");
    num2=console.nextInt();
    result=num1*num2;
    break;
    case'/':
    System.out.println("Please the first number");
    num1=console.nextInt();
    System.out.println("Please enter the second number");
    num2=console.nextInt();
    if(num2==0)
    System.out.println("Cannot Divide by Zero");
    result=num1/num2;
    break;
    //square root
    case'^':
    System.out.println("Please enter a number");
    break;
    //fibonacci     
    case'#':
    System.out.println("Please enter the position of the Fibonacci number");
    break;
    //factorial
    case'!':
    System.out.println("Please enter the number for factoring");
    break;
              //absolute value
    case'&':
    System.out.println("Please enter a number");
    num1=console.nextInt();
    result=num1;
    break;
         // help funtion
    case'?':
    System.out.println("Type + for addition, - for subtraction");
    System.out.println("* for multipliction, / for division,^ for the square root");
    System.out.println(" & for absolute value, # for fibonacci,and ! for factorial");
    break;
    System.out.println("The result is:"+result);     
    }

    rmabrey wrote:
    I have the calculator working but I am having trouble figuring out thow to do a square root function, nth factorial, absolute value, and Fibonacci. java.lang.Math.sqrt()
    nothing for factorial - write your own.
    java.lang.Math.abs()
    nothing for Fibonacci - write your own.
    %

Maybe you are looking for