gpt4 book ai didi

java - 当 struts.ognl.allowStaticMethodAccess 为 false 时,Struts 2 调用静态方法

转载 作者:行者123 更新时间:2023-11-30 07:07:15 29 4
gpt4 key购买 nike

出于安全问题,struts 2 将 struts.ognl.allowStaticMethodAccess 设置为 false。静态方法调用在某些情况下可能很有用,例如在处理表达式基 validator Struts 2 using StringUtils in validator expersions 时。 。

解决这个问题的一种方法是在操作中定义一个辅助方法,例如,如果我们想使用 Math 类,我们应该添加以下内容:

public double randomMath(){
return Math.random();
}


public double asinMath(double a){
return Math.asin(a);
}

....

并将其用作 ${randomMath}${asinMath(1)}

正如您所看到的,对于 Math 类中的每个方法,我们需要在操作中定义一个具有相同签名的 public 方法。

有没有更好的方法来避免这些样板 setter/getter ?!

最佳答案

OGNL 允许执行方法,但默认情况下禁用静态访​​问,因此不能在表达式中使用静态方法。但是,您可以告诉 OGNL 哪些类需要访问静态方法。

OGNL developer guide: Method Accessors

Method calls are another area where OGNL needs to do lookups for methods based on dynamic information. The MethodAccessor interface provides a hook into how OGNL calls a method. When a static or instance method is requested the implementor of this interface is called to actually execute the method.

public interface MethodAccessor
{

Object callStaticMethod( Map context, Class targetClass, String methodName, List args )
throws MethodFailedException;

Object callMethod( Map context, Object target, String methodName, List args )
throws MethodFailedException;

}

You can set a method accessor on a class-by-class basis using OgnlRuntime.setMethodAccessor(). The is a default method accessor for Object (which simply finds an appropriate method based on method name and argument types and uses reflection to call the method).

<小时/>

你可以编写一些东西

public class StringUtil extends StringUtils implements MethodAccessor {
//implement above methods
}
<小时/>

Action 类

public static final String MESSAGE = "hello.message";

/**
* Field for Message property.
*/
private String message;

/**
* Return Message property.
*
* @return Message property
*/
public String getMessage() {
return message;
}
private StringUtil stringUtil = new StringUtil();

public StringUtil getStringUtil() {
return stringUtil;
}

public String execute() throws Exception {
setMessage(getText(MESSAGE));
OgnlRuntime.setMethodAccessor(StringUtil.class, stringUtil);
return SUCCESS;
}
<小时/>

在 JSP 中

<s:if test="!stringUtil.isEmpty(message)">
<h2><s:property value="message"/></h2>
</s:if>
<小时/>

关于java - 当 struts.ognl.allowStaticMethodAccess 为 false 时,Struts 2 调用静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39875242/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com