struts-example.war 解壓重命名為 test)<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.cool</url-pattern> <!-- 自定義後綴 -->
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
ActionServlet 是 Struts 核心控制器,啟動時加載 struts-config.xml,攔截 *.cool 請求。
<form-beans>
<form-bean name="userForm" type="test.UserForm"/>
</form-beans>
<global-forwards>
<forward name="failed" path="/failed.cool"/>
<forward name="regist" path="/regist.jsp"/>
</global-forwards>
<action-mappings>
<action path="/regist" type="test.RegistAction" name="userForm" scope="request" input="/index.jsp"/>
<action path="/overview" forward="/hello.jsp"/>
<action path="/failed" forward="/wuwu.jsp"/>
</action-mappings>
request.getParameter()public class UserForm extends ActionForm {
private String name = "lpw";
private String ps = "1111";
// getter/setter 省略
}
屬性名與表單 name 屬性一一對應,Struts 自動填充。
public class RegistAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
UserForm userForm = (UserForm) form;
if ("lpw".equals(userForm.getName())) {
return mapping.findForward("failed"); // 邏輯名 → global-forwards
}
return mapping.findForward("regist");
}
}
業務邏輯極簡:驗證用戶名非默認值,決定轉向。
<form action="regist.cool" method="post">
用戶: <input type="text" name="name"><br>
密碼: <input type="password" name="ps"><br>
<input type="submit" value="新增用戶">
</form>
<a href="overview.cool">站點導航</a>
表單提交到 regist.cool,觸發 /regist Action Mapping。
<h1>site map</h1>The following is content filling by reader
<jsp:useBean id="beanlpw" class="test.UserForm" scope="session"/>
現有用戶:<%=beanlpw.getName()%><br>
密碼:<%=beanlpw.getPs()%><br>
沒有得到新的用戶!
<jsp:useBean id="beanlpw" class="test.UserForm" scope="session"/>
新用戶帳號:<%=beanlpw.getName()%><br>
密碼:<%=beanlpw.getPs()%>
https://localhost:8080/test/index.jspregist.coolActionServlet 攔截 → 查找 /regist mappingUserForm,自動填充請求參數RegistAction.execute(),執行業務邏輯ActionForward (邏輯名 "failed"/"regist")ActionServlet 解析 global-forwards → 轉發到對應 JSPjsp:useBean 讀取 session 中的 FormBean 顯示數據validate()、ActionErrors)struts-config.xml)html:form, bean:write, logic:iterate)