2013-03-25 50 views
1

我在JSP中有下面的一段scriptlet代碼。如何從pageContext中將屬性值轉換爲JSP內的scriptlet代碼

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

     } 
%> 

但是,我收到一個錯誤,說編譯時出現「:類型不匹配:無法從Object轉換爲String」。

有誰知道如何解決這個問題?

回答

4

這是因爲pageContext.getAttribute()返回一個Object。你必須將對象轉換爲字符串來解決這個問題:

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

OR

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

這是修改後的最終代碼應該是這樣的:

<% 
    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); 
    } 
%> 
+0

工作....謝謝! – 2013-03-25 13:03:40

+0

再次感謝你...... – 2013-03-25 13:08:50

0

嘗試鑄造成字符串:

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

這是告訴你你需要知道的一切。頁面上下文中的屬性爲Objects,則需要向下轉換爲String。做一個

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

但一切的目的是可愛的在這個世界上,避免使用scriplets並考慮JSTL