Search code examples
javajspenumsscriptlet

Why does my JSP scriptlet fail to retrieve an int from the pageContext and cast it to a locally scoped primitive variable?


I couldn't figure out a way to do this in EL/JSTL so when I do this:

<% 
int myIntPrimitiveValue = pageContext.getAttribute("myDataObject.myIntPrimitiveValue");
MyEnumObject myEnumInstance = myEnumObject.get(myIntPrimitiveValue);
String myEnumValueName = myEnumInstance.getName();
pageContext.setAttribute("myEnumValueName", myEnumValueName);
%>

I get this error:

Cannot cast from Object to int (line 1 in this snippet)

I know there's a valid value in myDataObject.myIntPrimitiveValue because I can print it like this with JSTL:

<c:out value="${myDataObject.myIntPrimitiveValue}"/>

What am I doing wrong here?


Solution

  • This is because:

    pageContext.getAttribute()
    

    returns Object

    What you need is converting the Object to int. For example:

    int myIntPrimitiveValue = Integer.valueOf("" + pageContext.getAttribute("..."));