Calling static method helper class in Struts2 JSP with Action data model value

前端 未结 2 1735
刺人心
刺人心 2020-12-21 04:50

I\'m a Struts2 newbie. I\'m using Struts2 with the typical datamodel UserItem inside an Action. The datamodel doesn\'t look good when using with the Struts ta

相关标签:
2条回答
  • 2020-12-21 05:28

    EDIT

    From 2.3.20 and higher, static method access won't work anymore, even if activated in the configuration.


    For static methods access you need:

    in Struts.xml

    <constant name="struts.ognl.allowStaticMethodAccess" value="true"/>
    

    in your JSP

    <s:property value="@com.your.full.package.Classname@methodName(optionalParameters)" />
    

    But as pointed out by rees, this should be avoided if not strictly necessary, because it's not a best practice.

    In your specific case, i guess the Object containing ["String1","String2",...] is a List, or a Vector, or something like this.

    Then all you need in your JSP is the <s:iterator> tag like this:

    <s:iterator name="yourObjectContainingAListOfString">
       <s:property /> 
       <br/>
    </s:iterator>
    
    0 讨论(0)
  • 2020-12-21 05:29

    For Static Method Access you must need to add following constant in your struts.xml file.

    <constant name="struts.ognl.allowStaticMethodAccess" value="true"/> 
    

    Example: struts.xml:

    <!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
    
    <struts>
        <constant name="struts.ognl.allowStaticMethodAccess" value="true"/>
        <package name="default"  namespace="/" extends="struts-default">
            <action name="sampleAction" class="vaannila.SampleAction">
                <result name="success">/WEB-INF/JSP/sample.jsp</result>
            </action>     
        </package>
    </struts>
    

    Then from your JSP you can access it in various ways:

    Example - 1:

    <b>Output :</b> <s:property value="@vaannila.SampleAction@getSTR()"/> <br>
    

    Where,

    1. vaannila = Package Name.
    2. SampleAction = Class Name.
    3. getSTR() = Method Name.

    Example - 2:

    <b>Output :</b> <s:property value="@vs@getSTR()"/> <br>
    

    Where,

    1. vs = Value Stack.
    2. getSTR() = Method Name.

    Example - 3:

    <b>Output :</b> <s:property value="%{STR}"/> <br>
    

    where,

    1. STR = STR is declared and initialized as Static String with getter and setter method in your Java Class
    0 讨论(0)
提交回复
热议问题