struts2中struts.xml和web.xml檔案解析及工作原理
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_9" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<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>
</web-app>
struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<!-- consant 常量,struts.devMode表示開發者模式,當為true時如果改變了其中的一些程式碼,可以不用重新啟動tomcat-->
<constant name="struts.devMode" value="true" />
<!--package可以有多個解決重名的情況, namespace 可以不寫,預設是如何路徑都可以,也可以寫成/xx/yy ,必須是/開頭-->
<package name="default" namespace="/" extends="struts-default">
<default-action-ref name="index" />
<global-results>
<result name="error">/error.jsp</result>
</global-results>
<global-exception-mappings>
<exception-mapping exception="java.lang.Exception" result="error"/>
</global-exception-mappings>
<!-- action裡面那個name屬性值得是URL輸入的路徑名 ,如“http://localhost:8080/Struts2Demo/hello”,則會根據result反饋Hello.jsp-->
<action name="hello" class="com.styspace.struts2.action.action2">
<result>
/Hello.jsp</result>
</action>
<!-- action裡面class屬性值,會有對應的這個類,執行該類裡面的execute()方法-->
<action name="action" class="com.styspace.struts2.action.action2">
<result name="success">/Action.jsp</result>
</action>
<!-- action裡面method屬性值,會有對應class這個類中的add方法,然後執行該方法-->
<action name="userAdd" class="com.bjsxt.struts2.user.action.UserAction" method="add">
<result>/user_add_success.jsp</result>
</action>
<!-- 一般action裡面不用method屬性值,而是用DMI(動態方法呼叫)可以通過http://localhost:8080/Struts2Demo/user!addURL呼叫,其中user指的是action中的name值-->
<action name="user" class="com.bjsxt.struts2.user.action.UserAction">
<result>/user_add_success.jsp</result>
</action>
<!-- 更簡單的方法,萬用字元,name=“student*”會匹配URL中所有Studentxx,而method=“{1}”指的是name中第一個“*”匹配的值 同理,result中{1}也是一樣的-->
<action name="Student*" class="com.bjsxt.struts2.action.StudentAction" method="{1}">
<result>/Student{1}_success.jsp</result>
</action>
<!-- 甚至可以有多個萬用字元,class屬性中也可以用{1}來匹配,最簡化-->
<action name="*_*" class="com.bjsxt.struts2.action.{1}Action" method="{2}">
<result>/{1}_{2}_success.jsp</result>
<!-- {0}_success.jsp -->
</action>
</package>
<!-- Add packages here -->
</struts>