Struts工作原理和核心配置

(一)            strurs的工作原理

1.       使用Jsp/Servlet时的流程

Jspà web.xml中配置的servlet Servlet-mapping找到对应的Servlet à Servlet(接受参数 验证 调用DAO等操作)à

跳转到不同的页面

 

2.       使用Struts时的流程

Jsp(提交到*.do) --> web.xml(通过*.do找到ActionServlet) -->ActionServlet(通过web.xmlActionServlet所在的配置中找到struts-config.xml)-->struts-config.xml (通过struts-config中的path路径找到 AcionFormAction )  -->

ActionForm(通过ActionForm中的validate方法验证,如果通过则进入Action 失败则通过input返回错误页-->

验证通过:Action(调用DAO进行逻辑判断,验证失败则通过input返回错误页 -->验证成功则通过Struts-config.xml中的forward跳转到相应的页面.

 

Struts流程图:


 

 

 

(二)            Struts的核心配置(struts-config.xml)

Struts-config.xml中的配置组

(1).

<form-beans >

    <form-bean name="loginForm" type="org.cgz.struts.form.LoginForm" />

</form-beans>

 

以上为ActionForm的配置

1.<form-beans/>中可以包含多个<form-bean/>

2.<form-bean/>中包含了2个属性: name->bean的名称 是此bean的唯一标识;type->bean的包.类名称

:通过此段代码可以读到form-bean 但看不出是如何跳转到form-bean中的.如何跳转到form-bean中在下面的

Action中会有体现

 

(2).

<data-sources />

以上是可以用来配置数据源连接,但struts中开发中一般不会去使用。

 

(3).

<action-mappings >

    <action

      attribute="loginForm"

      input="/login.jsp"

      name="loginForm"

      path="/login"

      scope="request"

      type="org.cgz.struts.action.LoginAction" >

      <forward name="login_success" path="/login_success.jsp" />

</action>

</action-mappings>

以上为Action的配置

1.<action-mappings />中可以包含多个<action>...</action>

2.nameattribute表示该Action对应的Actionformname属性(由此可以看出一个Action只能对应一个ActionForm,而一个ActionForm可以对应多个Action)

3.input 后面的页面是用来作为错误页的  validate方法验证失败后 会自动跳转到该页面

   :所有struts-config中配置的路径都必须加 / 表示从WebRoot下开始定义

4.path  表示该 Action的虚拟路径 必须加 /,且不能加.do的后缀(
       
servlet-mapping中的url-path 类似)

5.scope 表示action 所保存的属性范围 request表示每次请求重新建立新的action

6.type 表示action的包.类名

7. <forward ... /> action中可以包含多个不同的forward 路径  forward中的属性

Name forwar的唯一标识 Action代码中执行跳转时 需要通过其来查找对应的路径

Path 表示该 forward 所要跳转的路径

 

(4).

 

<message-resources parameter="org.cgz.struts.ApplicationResources" />

以上是用来配置资源文件所在的路径

资源文件的后缀名必须为 properties

 

(5)

<global-exceptions >

     <exception key="num" type="java.lang.NumberFormatException" path="exception"></exception>

</global-exceptions>

<global-forwards >

    <forward name="exception" path="/errors.jsp"></forward>

</global-forwards>

.以上是公共跳转路径和公共异常处理 一般不去使用

 

 

:一般情况下 需要手工配置的是Action中的 forward