Panadol Chong
Panadol Chong

Reputation: 1903

Assign a java object file value into jsp variable

The following is part of my jsp code:

${cForm.cId} <!-- I can see this value displayed correctly --%>
    <%! String i = ${cForm.cId}; %> 
    <td class="value">
        <img src="/supportcenter/cServlet?sampleImg=<%=i %>" width="300px" />
    </td>

cForm is my java object file, I can see the value displayed correctly in browser for the ${cForm.cId}.

However, when I want to assign the value into String i variable, I keep hit failed to compile : jsp error.

Kindly advise.

Upvotes: 1

Views: 9217

Answers (4)

Keerthivasan
Keerthivasan

Reputation: 12890

When you write a scriptlet, it just expects Java programming language. so, you should't put EL in it. You can assign the value to a page scoped attribute and get it in the scriptlet

 <c:set var="cFormId" value=${cForm.cId}/>
 <%
    String i = (String)pageContext.getAttribute("cFormId");   
  %>  

Note : Usage of Scriptlets is a bad practice. To solve your problem, just create the URL making use of EL value directly without beating around the bush

<img src="/supportcenter/cServlet?sampleImg=${cForm.cId}" width="300px" />

Upvotes: 2

user2575725
user2575725

Reputation:

you may try this if you simply want to append in the url without extra variable:

<td class="value">
  <img src="/supportcenter/cServlet?sampleImg=${cForm.cId}" width="300px" />
</td>

Upvotes: 1

Jason
Jason

Reputation: 11822

That is because the <% indicates the start of Java code (a scriptlet).

The ${...} notation (expression language) can't be used inside <% ... %> tags.

Upvotes: 0

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85789

You cannot mix expression language inside scriptlet. You should use scriptlet only or expression language only.

To fix your current error, retrieve the attribute from request (or wherever it is stored):

<% String i = ((CForm)request.getAttribute("cForm")).getId(); %>

To really solve your problem: stop using scriplets at all, keep it all in expression language:

<img src="/supportcenter/cServlet?sampleImg=${cForm.cId}" width="300px" />

Upvotes: 5

Related Questions