ITEEDU

Struts Gossip: 讯息管理

在Struts中可以在一个讯息资源文件中统一管理讯息,您可以在struts-config.xml中设定资源文件名称及位置,例如:
struts-config.xml
<?xml version="1.0" encoding="ISO-8859-1" ?>

<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.2//EN"
"http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd">
<struts-config>
    <action-mappings>
        <action
             path="/hello"
             type="onlyfun.caterpillar.HelloAction">
             <forward
                 name="helloUser"
                 path="/WEB-INF/pages/hello.jsp"/>
         </action>
     </action-mappings>
   
    <message-resources parameter="resources/messages"/>
</struts-config>
在<message-resources>卷标中设定了资源文件位置为 resources/messages,这表示将使用CLASSPATH下的resources/messages.properties档案,例如您可 以将之放在/WEB-INF/resources/messages.properties下,资源档内容如下:
messages.properties
welcome.helloWord=Hello!
welcome.message=This is your secret gift!!
配合讯息资源文件,来写个简单的 Action 测试一下讯息管理:
HelloAction.java
package onlyfun.caterpillar;

import java.util.*;
import javax.servlet.http.*;
import org.apache.struts.action.*;
import org.apache.struts.util.MessageResources;

public class HelloAction extends Action {
public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {

MessageResources messageResources =
getResources(request);

String helloWord =
messageResources.getMessage("welcome.helloWord");
String message =
messageResources.getMessage("welcome.message");

// get information from request object
String username = request.getParameter("user");

// prepare model
Map model = new HashMap();
model.put("helloWord", helloWord);
model.put("message", message);

if(username != null)
model.put("username", username);
else
model.put("username", "nobody");

// pass information to View by using reqeust object
request.setAttribute("userInfo", model);

// no more carrying information from client
request.removeAttribute("user");

return mapping.findForward("helloUser");
}
}
这边使用继承Action下来的getResources()取得一个MessageResources对象,当中包括了 messages.properties的讯息,然后使用它的getMessage()指定键值来取得对应讯息,来写一个简单的JSP网页测试一下:
hello.jsp
<html> 
<head>
<title>
${userInfo["helloWord"]} ${userInfo["username"]}!
</title>
</head>
<body>

<H1>${userInfo["helloWord"]} ${userInfo["username"]} !</H1>
<H1>${userInfo["message"]}</H1>

</body>
</html>
依上面的设定,如果依下面的方式请求:
http://localhost:8080/strutsapp/hello.do?user=Justin
则将传回以下的结果:

<html> 
<head> 
<title>
     Hello! Justin !
</title> 
</head> 
<body>

<H1>Hello! Justin !</H1>
<H1>This is your secret gift!!</H1>

</body> 
</html>