Call a static helper method class in Struts2 JSP with action data model value

I am new to Struts2. I am using Struts2 with a typical datamodel UserItem inside an Action. Datamodel does not look good when used with the Struts <s:property value="userItem.foo"/> .

What I want to do is write the static util Helper.printNice(Foo) method, which takes the Foo parameter and displays the value contained in Foo in a user-friendly display.

How to use a Struts property tag with a static method? Something like this com.helper.Helper.printNice(<s:property value="userItem.foo"/>) .

The reason for this is that my web application reads data filled out by a provider that looks like this ["string1", "string2", ...] in many columns. Obviously, I do not want to display the end user in this format. The helper method will make it look like string1 <br> string2 <br>, etc ...

+4
source share
2 answers

EDIT

From 2.3.20 and higher , access to the static method will no longer work , even if it is activated in the configuration.


To access static methods you need to:

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 noted by the flight, this should be avoided, if not strictly necessary, because this is not the best practice.

In your particular case, I assume that the Object containing ["String1", "String2", ...] is a List or Vector, or something like that.

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

 <s:iterator name="yourObjectContainingAListOfString"> <s:property /> <br/> </s:iterator> 
+7
source

To access the static method, you need to add a constant to struts.xml .

 <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

  • vaannila = The name of the package.
  • SampleAction = The name of the class.
  • getSTR() = Method name.

Example 2:

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

Where

  • vs = Column of values.
  • getSTR() = Method name.

Example 3:

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

Where

  • STR = STR declared and initialized as a Static String using the getter and setter method in your Java class
+1
source

Source: https://habr.com/ru/post/1442226/


All Articles