在Struts 2中抛出NullPointerException的getText()方法

时间:2017-02-01 13:14:55

标签: java properties nullpointerexception struts2 localization

我有一个包含

package.properties文件
email.domain=localhost:8080

现在,从同一个包中的一个类我调用getText("email.domain")但是收到此错误:

堆栈跟踪:

System.out.println("http://" + getText("email.domain") + "/ReportContent.action");

java.lang.NullPointerException
        at com.opensymphony.xwork2.util.LocalizedTextUtil.findText(LocalizedTextUtil.java:361)
        at com.opensymphony.xwork2.TextProviderSupport.getText(TextProviderSupport.java:208)
        at com.opensymphony.xwork2.TextProviderSupport.getText(TextProviderSupport.java:123)
        at   com.opensymphony.xwork2.ActionSupport.getText(ActionSupport.java:103)

如何解决此问题?

3 个答案:

答案 0 :(得分:0)

您可以在映射到当前线程中正在执行的请求的操作的上下文中仅调用getText

如果您要加载属性,可以使用Properties类和方法load()

答案 1 :(得分:0)

下面是一个从Maven存储库创建的典型Struts2项目。

enter image description here

我的所有Action类都将在 com.xxx.controller 包中提供。

要使其工作在getText(“xxxxxx”)方法中,需要进行以下配置。

  1. 您的行为应直接或间接延伸ActionSupport
  2. 与struts.xml一起,您应该将struts.propertiesXXXXX.properties文件放在放置struts.xml的位置
  3. struts.properties中的配置是
  4.   

    struts.custom.i18n.resources =<附加属性的文件名   没有扩展名的文件名>   示例:struts.custom.i18n.resources = package.properties;

    1. 需要在struts.xml中完成配置:
    2.   

      < constant name =“struts.custon.i18n.resources”   value =“XXXXX”/>

           

      示例 =< constant name =“struts.custon.i18n.resources”value =“package”/>

      检查项目中正确配置的所有这些配置。

答案 2 :(得分:0)

ActionSupport.getText()最终会呼叫ActionContext.getContext().getValueStack()。您的NullPointer是因为ActionContext.getContext()为空。例如,当您自己创建ActionSupport对象时,可能会发生这种情况……可能是通过执行类似ActionSupport myActionSupportObj = new ActionSupport()的操作;假设其余的struts2设置均已完成,则获取有效的ActionSupport对象的适当方法是重写AbstractInterceptor类

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionSupport;

public class MyInterceptor extends AbstractInterceptor {
    @Override
    public String intercept(ActionInvocation invocation) throws Exception {
        ActionSupport actionInstance = (ActionSupport) invocation.getAction();