简体   繁体   中英

How can I take the attribute value from pageContext to the scriptlet code inside my JSP

I have the below piece of scriptlet code in my JSP.

<%   
      String instockMessage = pageContext.getAttribute("instockMessage");
      if ((instockMessage != null) && (instockMessage.trim().length() != 0)) {
            instockMessage = instockMessage.replaceAll("<[^>]*>", "").trim();
            pageContext.setAttribute("instockMessage", instockMessage);

      }
%>

But, I am getting an error saying that “: Type mismatch: cannot convert from Object to String” on compilation.

Does anyone knows how to fix this issue?

This is because the pageContext.getAttribute() returns an Object. You have to Cast the Object to String to fix this issue:

String instockMessage = (String) pageContext.getAttribute("instockMessage");

OR

String instockMessage = pageContext.getAttribute("instockMessage").toString();

That is after modification your final code should look like this:

<%  
    String instockMessage = pageContext.getAttribute("instockMessage").toString();
    if ((instockMessage != null) && (instockMessage.trim().length() != 0)) {
        instockMessage = instockMessage.replaceAll("<[^>]*>", "").trim();
        pageContext.setAttribute("instockMessage", instockMessage);
    }
%>

OR

<%  
    String instockMessage = (String) pageContext.getAttribute("instockMessage");
    if ((instockMessage != null) && (instockMessage.trim().length() != 0)) {
        instockMessage = instockMessage.replaceAll("<[^>]*>", "").trim();
        pageContext.setAttribute("instockMessage", instockMessage);
    }
%>

尝试转换成字符串:

String instockMessage = (String) pageContext.getAttribute("instockMessage");

It's telling you everything you need to know. The attributes from the page context are Objects , you need to downcast to a String . Do a

String instockMessage = (String) pageContext.getAttribute("instockMessage");

But for the sake of everything that is lovely in this world, avoid using scriplets and look into JSTL .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM