How can I pass a server side variable into a core tag in JSP?

扶醉桌前 提交于 2019-12-10 17:30:13

问题


This expression tag outpus a correct value for me <%=drug.NonAuthoritative%>

while I cant recover the value of drug.NonAuthoritative for use in a C tag

<c:if test="${drug.NonAuthoritative}">&nbsp;<bean:message key="WriteScript.msgNonAuthoritative"></bean:message></c:if>

the method is

public Boolean NonAuthoritative() {
    return nonAuthoritative;
}

回答1:


There are 2 problems:

  1. Scriptlets and EL do not share the same scope. The drug in ${drug} has to match the name of an existing attribute in the page, request, session or application scope. If you're preparing drug in a scriptlet instead of in a controller, then you should put it as an attribute in one of those scopes yourself.

    <% 
        Drug drug = new Drug();
        // ...
        request.setAttribute("drug", drug);
    %>
    

  2. (as partly answered by Nathan), EL relies on Javabeans specification. The ${drug.propertyName} requires a public method getPropertyName() for non-boolean properties or isPropertyName() for boolean properties. So, this should do

    public class Drug {
    
        private boolean nonAuthorative;
    
        public boolean isNonAuthorative() {
            return nonAuthorative;
        }
    
        // ...
    }
    

    with

    <c:if test="${drug.nonAuthoritative}">
    

    (pay attention to the casing!)




回答2:


The scriptlet <%=drug.NonAuthoritative%> uses the field NonAuthoritative of the drug instance.

The EL expression ${drug.NonAuthoritative} uses the method isNonAuthoritative() of the drug instance.

To make this work, keep the EL expression as-is, but add this method to your drug class:

public boolean isNonAuthoritative() {
  return NonAuthoritative;
}



回答3:


That's because the JSTL is assuming you're using JavaBean standards, so when you call something drug.NonAuthoritative in a JSTL expression it's looking for a method called getNonAuthoritative() (or alternatively isNonAuthoritative()). The scriptlet doesn't make that assumption, it just evaluates what you give it.



来源:https://stackoverflow.com/questions/5859023/how-can-i-pass-a-server-side-variable-into-a-core-tag-in-jsp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!