Struts學習傻瓜式入門篇
|
或許有人覺得struts不容易學,似乎里面的一些概念讓未接觸過的人迷惑,MVC1、MVC2、模式……我寫這篇文章是想讓從來沒有接觸過struts的人,能有個簡單的入門指引,當然,系統地學習struts是必要的,里面有很多讓人心醉的東東,那是后話了。
該案例包括首頁,用戶登陸、網站向導頁面。就這么簡單,沒有深奧的struts概念,主要靠動手,然后用心體會。
WEB Server用tomcat4。到http://jakarta.apache.org下載struts1.1,把zip文件釋放到c:struts,拷貝C:strutswebappsstruts-example.war到c:omcat4webapps中,啟動tomcat,war包被釋放為struts-example文件夾,刪除war包,把struts-example文件夾更名為test。
一、把WEB-INFweb.xml改成:
<?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN" "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd"> <web-app> <!—這是struts中的Controller(控制器),系統的指令中轉由其,既ActionServlet 類負責,它從struts-config.xml中讀取配置信息,并在服務器后臺自動啟動一個線程。如果沒有特別的要求(如添加語言編轉功能),程序員可以不管這部分,照用就可以了。--> <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可以映射成cool為后綴的文件,而不是常見的.jspdo等,后綴名可以改成任何名稱,當然名字要健康#◎¥%!--> <servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>*.cool</url-pattern> </servlet-mapping> <!--該系統的默認首頁是index.jsp,可以有多個,系統按次序找,類似IIS--> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app> |
二、把testWEB-INF struts-config.xml改成:
<?xml version="1.0" encoding="ISO-8859-1" ?> <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd"> <struts-config> <!--FormBean是struts的一個概念,本質是JavaBean,用來自動存儲頁面表單中各個域的值,并在適當的時候回填表單域,不需要象傳統那樣request.getParameter(“fieldName”);,常被action-mappings中的action 使用--> <form-beans> <!—稍后我們會新增一個UserForm類,用來存儲用戶信息。--> <form-bean name="userForm" type="test.UserForm"/> </form-beans> <!--這里存放整個系統都可以使用的全局轉向中轉(Forward)地址,類似于javascript中的window.location(‘index.jsp’);,也類似于電視控制器上的各種按鈕,可以轉頻道、調色等等是基于Struts的Web應用的控制流程流轉。一般情況下,一個Action處理完畢后,會轉發到一個JSP頁面進行顯示。這也是JSP中的MVC的實現的要點。--> <global-forwards> <!--failed.cool將被當成servlet請求,到action-mappings中尋找對應的action處理。--> <forward name="failed" path="/failed.cool"/> <forward name="regist" path="/regist.jsp"/> </global-forwards> <!--還記得web.xml中后綴為cool的請求嗎?它們是轉到這里處理的。這里相當于struts的Model部分,Model部分是struts中比較靈活的地方。--> <action-mappings> <!--處理regist.cools的請求,使用的FormBean是userForm,既test.UserForm類,當處理過程發生錯誤時將返回index.jsp--> <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> </struts-config> |