Creating immutable objects in JSP

I know you can use a tag <jsp:useBean>

to create objects in JSP without scripting code. However, I would like to create an Integer instance whose value is the result of an EL expression, for example:

<jsp:useBean id="total" class="java.lang.Integer">
    <jsp:setProperty name="amount" value="${param1 + param2}"/>
</jsp:useBean>

      

Of course, this will not work, because Integer objects do not have a property named "amount", the only way that their value can be set is through a constructor parameter (ie Integer objects are immutable). Is there a way to instantiate such an object and set its value without scripting code?

Thanks Don

+1


source to share


3 answers


<c:set var="amount" value="${param1 + param2}" scope="page" />



+1


source


Primitive wrappers also don't have a default constructor, so you can't even initialize it.

I'm not sure if EL should be used this way. It's more of a templating language. It is not clear what the use of what you are trying to do has something like:

<%
  Integer total = new Integer(param1 + param2);
%>

      



And then just use <% = total%> where you want the value to be output. You can also do:

<%
  pageContext.setAttribute("total", new Integer(param1 + param2));
%>

      

if you want the value to be in page scope like useBean.

+1


source


If you have a bean, can you just update the bean with param1 and 2? Create a method setAmount (param1, param2) and set it before using getAmount (), which will be called by the bean.

0


source







All Articles