假设我有一个带有定义值 uploads.directory 的 struts.properties 文件。如何以编程方式从 Actioncontext 访问该值?
6 回答
您可以使用 getText("some.property.name") 返回属性值
http://struts.apache.org/maven/struts2-core/apidocs/com/opensymphony/xwork2/ActionSupport.html
创建ActionSupport
对象并使用类的getText()
方法ActionSupport
。
ActionSupport actionSupport = new ActionSupport();
actionSupport.getText("foo.bar");
Create a resources folder under src
.
In the struts.xml
file add a constant e.g., <constant name="struts.custom.i18n.resources" value="global"></constant>
Here global is the name of properties file.
Now you will be able to use the properties in the entire application.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<!-- constant to define result path locations to project root directory -->
<!-- constant to define global resource bundle -->
<constant name="struts.custom.i18n.resources" value="global"></constant>
<package name="user" namespace="/" extends="struts-default">
<action name="home">
<result>/home.jsp</result>
</action>
<action name="welcome" class="com.waqar.struts2.actions.WelcomeAction">
<result name="success">/welcome.jsp</result>
</action>
</package>
</struts>
The welcome.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title><s:property value="getText('action.welcome.title')"/></title>
</head>
<body>
<s:property value="getText('action.welcome.username')"/>: <s:property value="username"/><br>
</body>
</html>
global.properties
action.welcome.username=waqar
In action class
System.out.println(getText("action.welcome.username"));
您需要将 my.properties 文件或 my_locale.propeties 文件放在包含您的操作类的包中。
您需要将值放在除 struts.properties 之外的属性文件中,例如ApplicationResources.properties
,或者my.properties
需要在类路径中。struts.properties 文件用于加载 struts 特定的属性,例如struts.i18n.encoding=UTF-8
等struts.devMode = false
。
在为自定义消息创建属性文件之后,您需要在 struts.properties 中做的事情是您必须在 struts.properties 文件中添加以下属性
struts.custom.i18n.resources=ApplicationResources
如果您有多个自定义消息属性文件,则需要通过逗号分隔来添加它们,例如:
struts.custom.i18n.resources=ApplicationResources,my
然后在您的操作类中,您可以使用getText('propertyName')
您可以像这样从消息资源文件中获取值:
public class MyAction extends ActionSupport {
public String getUserDetails() {
if("First Name".equals(getText("label.firstName"))) {
System.out.println("In if block");
}
}
}
您还可以获得更多信息,如何从.properties
java 类或 jsp 文件中的文件中获取值。对于 JSP:
<s:text name="label.firstName" />
和
<s:property value="getText('label.age')" />
有关更多信息,您可以通过此链接: 在此处获取信息