Java綠地(~ming~)

          Java 草地

          常用鏈接

          統(tǒng)計

          最新評論

          Struts原理實(shí)例

          STRUTS

          1.WEB-INF中需要的配置(主要是實(shí)例化ActionServlet---struts-config.xml)

          a. 如果標(biāo)簽不能識別:<jsp-config>

              <taglib>    <taglib-uri>http://java.sun.com/jstl/core</taglib-uri>

                      <taglib-location>/WEB-INF/c.tld</taglib-location>    </taglib>

          b.配置歡迎頁面: <welcome-file-list> <welcome-file>/logon.jsp</welcome-file>

                          </welcome-file-list>

          c.ActonServlet主要配置: <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>

          </servlet>

          <servlet-mapping>   <servlet-name>action</servlet-name>

                                    <url-pattern>*.do</url-pattern>     </servlet-mapping>

          2.struts-config.xml配置:(主要為中央處理器建立關(guān)聯(lián))

          a. <action-mappings >    <action

                path="/logon"  scope="request" type="mypack.action.LogonAction"

          attribute="logonForm" name="logonForm"      input="/logon.jsp">   

          <forward name="show" path="/AddAssociate.jsp" />

                <forward name="failure" path="/logon.jsp" />    </action>

          b.<form-beans >

          <form-bean name="logonForm" type="mypack.struts.form.LogonForm" /> </form-beans>

          c.resource文件:<message-resources parameter="mypack.struts.ApplicationResources" />



          3.
          通過ActionFormvalidate方法若驗(yàn)證通過才創(chuàng)建action實(shí)例:

          public ActionErrors validate(ActionMapping mapping,HttpServletRequest request) {

          ActionErrors errors=new ActionErrors();if(userName==null){ //ActionMessage為父類

          errors.add(“contant”,new ActionMessage(“resource.key”));//ActionErrors唯一方法

          return errors;}

          ActionErrorsActionMessages子類,add方法必須為ActionError,1.2采用ActionMessage

          4.雖然ActionServlet只有一個,但是通過配置組件ModuleConfig來創(chuàng)建具體子模塊處理器RequestProcessor,Action負(fù)責(zé)處理具體業(yè)務(wù)并通過ActionForward返回合適的結(jié)果.

          : public class LogonAction extends Action {

              public ActionForward execute(ActionMapping mapping, ActionForm form,

                      HttpServletRequest request, HttpServletResponse response) {

          LogonForm logonForm = (LogonForm) form;   ActionErrors errors = new ActionErrors();

          ActionForward forward = new ActionForward();

          String userName = (String) (logonForm.getUserName()); if (!(userName.equals("admin"))

           errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionError("logonagain"));

          if (!errors.isEmpty()) {

          saveErrors(request, errors);   // saveErrors方法(request,errors必為ActionErrors)

               forward = mapping.findForward("failure");}

          else { HttpSession session = request.getSession();

          session.setAttribute("user", userName);forward = mapping.findForward("show");}

          return forward;    }}




          5.DAO
          訪問數(shù)據(jù)庫的模型:

          a.public class ConnectDB {  public static Connection getConnection(){

          Connection conn=null;try{ Class.forName(driver);       

                      conn=DriverManager.getConnection(url,user,password);}

          catch(Exception e){e.printStackTrace();}    return conn;    }}

          b.因?yàn)?span lang=EN-US>ActionForm中的數(shù)據(jù)生命周期只能到Action,于是只有通過action繼續(xù)傳遞

          AssociateForm associateForm = (AssociateForm) form;

          String associateId=associateForm.getAssociateId();

          String name=associateForm.getName();AssociateDao associateDao=new AssociateDao();

          associateDao.addAssociateDao(associateId,name);將參數(shù)傳遞到DAO

          c.DAO中插入數(shù)據(jù): public void addAssociateDao(String associateId,String name) {  Connection  conn=ConnectDB.getConnection();

          String sql="insert into associateInfo(associateId,name) values(?,?)";

              PreparedStatement pstmt=null; (try) pstmt=conn.prepareStatement(sql);

              pstmt.setString(1,associateId);pstmt.setString(2,name);pstmt.execute();




          6.
          訪問數(shù)據(jù)庫:a.jsp頁面的標(biāo)簽: jstl<c:set/>標(biāo)簽調(diào)用DAOget方法并存在一定的范圍

          <jsp:useBean id="associateDao1" class="mypack.dao.AssociateDao" scope="page"/>

          <c:set var="associates" value="${associateDao1.associateDao}" scope="page"/>

          b. public Collection  getAssociateDao() throws SQLException{

              Connection   conn=ConnectDB.getConnection();

              Statement stmt=conn.createStatement();String sql="select * from associateInfo";

              ResultSet rs=stmt.executeQuery(sql);    List associateList=new ArrayList();

              while(rs.next()){Associate temp=new Associate();//需要創(chuàng)建一個模型層數(shù)據(jù)中介     temp.setAssociateId(rs.getString("associateId"));

          temp.setName(rs.getString("name"));associateList.add(temp);}//將數(shù)據(jù)全部封裝

              stmt.close();conn.close();  return associateList;  }

          c. <logic:iterate id="associate" name="associates" >  //<logic:iterate/>迭代集合

               <td><bean:write name="associate" property="associateId" /></Td>

               <td><bean:write name="associate" property="name" /></Td>   </logic:iterate>



          7.
          validator框架實(shí)現(xiàn)驗(yàn)證:

          a.jsp頁面:  <html:form action="/valid" onsubmit="return validatevalidForm(this)" />

                      <html:javascript formName="validForm"/>

          b.struts-config.xml中配置插件: <plug-in className="org.apache.struts.validator.ValidatorPlugIn">

              <set-property property="pathnames" value="/WEB-INF/validator-rules.xml,/WEB-INF/valid.xml" />  </plug-in>

          c. valid.xml的配置: <form-validation>

              <global>    <constant><constant-name>phone</constant-name>//設(shè)置全局變量

                       <constant-value>^\d{8}\d*$</constant-value>    </constant> </global>

              <formset> <form name="validForm">

                  <field property="phone" depends="required,mask">//通過變量驗(yàn)證的字段名

                      <var> <var-name>mask</var-name> <var-value>${phone}</var-value> </var>

                      <arg0 key="lable" />    </field>            </form> </formset>

          </form-validation>

          d. properties文件的key:errors.required ={0} 為必填   lable=用戶名   //{0}arg0為參數(shù)

          備注:正則表達(dá)式:

          *

          匹配0或多次,對鄰近一個()起作用

          Ab*:a,abb

          +

          匹配>=1,對鄰近一個()起作用

          Ab+:ab,abb

          ?

          匹配0或一次, 對鄰近一個()起作用

          Ab?:a,ab

          {n}

          匹配指定的次數(shù), 對鄰近一個()起作用

          Ab{2}c:abbc,aabbc

          {n,m}

          匹配從nm, 對鄰近一個()起作用

          Ab{2,3}c:abbc,abbbc

          ^(也表示字符串頭)

          不想匹配的字符,一般和[]一起

          A[^b]c:adc,aec

          $(字符串結(jié)束位置)

          ^\w+$:為一個或多個數(shù)字,字母

          ^\d{8}\d*$:只能8位數(shù)字

          表示一個范圍

          [09]:0,1…9

          \d

          等價于[09]表示一個數(shù)字

          \da:1a,2a

          \D

          等價于[^09],不能為數(shù)字

          \Da:aa,da

          \w

          等價于[AZ09]匹配單個數(shù)字或字母

          \wa:1a,va

          \W

          等價于[^AZ09]不匹配單個數(shù)字或字母

          \Wa:!a,#a

          \

          轉(zhuǎn)義字符

          \.表示.




          8
          STRUTS國際化:

          a.全部設(shè)為UTF-8編碼:<%@ page language="java" contentType="text/html;charset=UTF-8" %>

          b.bat文件: native2ascii –encoding gb2312 ori.properties target.properties



          9.
          存放常量共享數(shù)據(jù):

            a.存放常量的java文件:public final class Constants{

          public static final String PERSON_KEY=”personbean”;}

            b.Action中保存數(shù)據(jù):request.setAttribute(Constants.PERSON_KEY,class);

            c.在頁面輸出:<logic:present name="personbean" scope="request" >

                         <bean:write name="personbean"  property="userName"/></logic:present>



          10
          .輸出下拉菜單組:<jsp:useBean id="groupDao" class="mypack.GroupDao" scope="page"/>

                             <c:set var="groups" value="${groupDao.groups}" />  //get方法

          <td><html:select property="groupId">  //讀取數(shù)據(jù)庫中的groupName屬性

          <html:options collection="groups" property="groupId" labelProperty="groupName" />

          </html:select></td>




          11
          Struts內(nèi)置對象


          aforwardAction:(請求—ActionForm—Action—ActionForm—響應(yīng))

          頁面:<html:form action="/forward"><html:text property="userName"/> <html:submit/>

          配置:<action  input="/hello.jsp"   name="forwardForm"

                 path="/forward" parameter="/forward.jsp"      scope="request"

                 type="org.apache.struts.actions.ForwardAction">    </action>

          輸出:${forwardForm.userName}//在配置中的<form-beans >實(shí)例化

          bDispatchAction(用于不同的表單響應(yīng)同一個Action

          頁面:<html:form action="/personManager" >

                <html:hidden  property="method" value="addPerson" />

                <html:text  property="person.password"  />

                <html:submit value="add"/> </html:form>

               <html:form action="/personManager" >

                <html:text  property="person.password" />

               <html:submit property="method" value="updatePerson"/>  </html:form>

          配置:<action path="/personManager"

                 type="mypack.struts.action.MyDispatchAction" //繼承DispatchAction

                 parameter="method"   name="forward2Form"    scope="request"

                 input="/dispatch.jsp"  >

               <forward name="success" path="/success.jsp"></forward>    </action>

          <action>中根據(jù)value自動映射:public ActionForward addPerson(){ }

                                public ActionForward updatePerson( ){ }

          輸出:${forward2Form.person.password }

          備注:DispatchAction參數(shù)根據(jù)表單中的property映射,具體值由value傳入。

           

          cLookupDispatchAction(同一個表單不同的觸發(fā)事件)

          頁面:<html:form action="/personManager2">

                <html:text property="person.password"  />

                <html:submit property="action"   value="addPerson" />

                <html:submit property="action">

                <bean:message key="button.update.person" />   </html:submit> </html:form>

          配置:<action path="/personManager2"   parameter="action"

                type="mypack.struts.action.MyLookupDispatch"

                name="forward2Form"    scope="request"    input="/dispatch.jsp"  >

               <forward name="success" path="/success.jsp"></forward>   </action>

          資源文件:button.add.person=addPerson    button.update.person=updatePerson

           

          Action(重寫父類LookupDispatchAction抽象方法): protected Map getKeyMethodMap() {

                  Map map=new HashMap();   map.put("button.add.person", "addPerson");

                  map.put("button.update.person", "updatePerson");       return map;  }

          public ActionForward addPerson(){ }

          public ActionForward updatePerson( ){ request.setAttribute("ok", "update"); }

          輸出:${ok }

          備注:LookupDispatchAction的映射由getKeyMethodMap方法建立,具體值也由value傳入

          posted on 2007-07-16 12:56 mrklmxy 閱讀(1172) 評論(0)  編輯  收藏


          只有注冊用戶登錄后才能發(fā)表評論。


          網(wǎng)站導(dǎo)航:
           
          主站蜘蛛池模板: 嵊泗县| 皮山县| 南投市| 汝州市| 安泽县| 鲁甸县| 阳山县| 宁河县| 襄汾县| 公主岭市| 武穴市| 九江县| 柳州市| 揭东县| 慈溪市| 陆川县| 甘德县| 苗栗县| 凤冈县| 娱乐| 得荣县| 黄浦区| 黄龙县| 马关县| 潢川县| 荔浦县| 双辽市| 汉中市| 荆州市| 福海县| 封丘县| 榆社县| 江川县| 高清| 射洪县| 抚宁县| 筠连县| 礼泉县| 出国| 鱼台县| 巴塘县|