Servlet 規範提供兩種保護資源方式:web.xml 宣告式配置(靈活、無需改碼)與 Java 硬編碼。Struts 2 建立於 Servlet 之上,自然繼承宣告式安全機制。
編輯 $CATALINA_HOME/conf/tomcat-users.xml:
<tomcat-users>
<role rolename="tomcat"/>
<role rolename="role1"/>
<user username="tomcat" password="tomcat" roles="tomcat"/>
<user username="both" password="tomcat" roles="tomcat,role1"/>
<user username="role1" password="tomcat" roles="role1"/>
</tomcat-users>
定義 2 角色、3 用戶,both 擁有雙重權限。
<security-constraint>:保護資源與授權角色<security-constraint>
<web-resource-collection>
<web-resource-name>Admin Area</web-resource-name>
<url-pattern>*.action</url-pattern> <!-- 所有 .action 請求受保護 -->
</web-resource-collection>
<auth-constraint>
<role-name>myeclipseWeb</role-name> <!-- 僅此角色可訪問 -->
</auth-constraint>
<!-- 可選:傳輸保障 NONE | INTEGRAL | CONFIDENTIAL -->
</security-constraint>
url-pattern 至少一個,支援多個;http-method 可選,限制特定 HTTP 方法(如僅限 POST);auth-constraint 缺失 = 所有角色可訪問;user-data-constraint 可設 CONFIDENTIAL 強制 HTTPS。<login-config>:指定認證方式<login-config>
<auth-method>BASIC</auth-method> <!-- BASIC | DIGEST | FORM | CLIENT-CERT -->
<realm-name>User Basic Authentication</realm-name>
</login-config>
若用 FORM 需額外配置 form-login-page / form-error-page。
<security-role>:聲明角色存在<security-role><role-name>myeclipseWeb</role-name></security-role>
<security-role><role-name>myeclipseWebservices</role-name></security-role>
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="https://java.sun.com/xml/ns/j2ee">
<display-name>Struts Blank</display-name>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list><welcome-file>index.html</welcome-file></welcome-file-list>
<!-- 安全約束 -->
<security-constraint>
<web-resource-collection>
<web-resource-name>Admin Area</web-resource-name>
<url-pattern>*.action</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>myeclipseWeb</role-name>
</auth-constraint>
</security-constraint>
<security-role><role-name>myeclipseWeb</role-name></security-role>
<security-role><role-name>myeclipseWebservices</role-name></security-role>
<login-config>
<auth-method>BASIC</auth-method>
<realm-name>User Basic Authentication</realm-name>
</login-config>
</web-app>
SecureAction(含 username 屬性);struts.xml 映射 /secure.action → SecureAction → /index.jsp;input.jsp 提交表單至 secure.action;input.jsp → 提交 → 彈出 BASIC 認證框;webservices(無 myeclipseWeb 角色)→ 403 Forbidden;admin(擁有角色)→ 成功顯示 Welcome, Tom。中文亂碼提示:若需傳遞中文參數,請將 Struts 2 預設編碼與頁面編碼統一修改為
GBK或UTF-8(現代專案建議全鏈路 UTF-8)。