Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate the total of a sum in JSTL [duplicate]

How can I realise this with JSP and JSTL?

int total = 0;
for (Article article : list) {
    total += article.price;
}
like image 523
Alex Avatar asked Dec 03 '14 14:12

Alex


People also ask

How to calculate sum in JSP?

Basically, here we use HTML input fields to accept the numbers from the user. Therefore, in the code, first we check whether the input fields have values or not. In case, user has entered the values and clicks on the Find Sum button, we call the find_sum() method to compute the sum and display it on the same page.

How to calculate sum of column in JSP?

SQL COUNT() SyntaxSELECT SUM(column_name) FROM table_name; In this example we count how many Row in the students_data table.

What is the syntax for forEach loop in JSTL?

Full Stack Java developer - Java + JSP + Restful WS + Spring The <c:forEach> tag is a commonly used tag because it iterates over a collection of objects. The <c:forTokens> tag is used to break a string into tokens and iterate through each of the tokens.

What is C set in JSTL?

3.2. The <c:set> tag is used for declaring scoped variables in JSP. We can also declare the name of the variable and its value in the var and value attributes respectively. An example will be of the form: <c:set value="JSTL Core Tags Example" var="pageTitle"/>


1 Answers

Use <c:set> to initialize the total variable, use <c:forEach> to iterate over list and use another <c:set> to add the iterated value to the total.

<c:set var="total" value="${0}"/>
<c:forEach var="article" items="${list}">
    <c:set var="total" value="${total + article.price}" />
</c:forEach>

See also Iterate over elements of List and Map using JSTL <c:forEach> tag.

like image 125
Semih Eker Avatar answered Oct 04 '22 06:10

Semih Eker