Question

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.

Was it helpful?

Solution

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" />

OTHER TIPS

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" />

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>

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

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top