訊息管理


在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/classes/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>