使用Struts2框架準(zhǔn)備工作

1.導(dǎo)入相關(guān)jar包

  1. Struts2配置核心過(guò)濾器

使用Struts2需要在lib下的web.xml中配置核心過(guò)濾器
代碼如下:

  <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>
  1. 配置src下struts.xml
    <package>標(biāo)簽是為了將Action配置封裝起來(lái),一個(gè)<package>標(biāo)簽下可以配置多個(gè)action
    <package>標(biāo)簽下的name屬性是給包取得名字,起到標(biāo)識(shí)作用,可以隨便起,不能與其他包名重復(fù)
    namespace屬性是給action的訪問(wèn)路徑定義一個(gè)命名空間,在前端頁(yè)面使用action時(shí)需要加上命名空間名字如果給命名空間命名為/hello那么在前端頁(yè)面中應(yīng)該href = "/hello/Action.action"
    命名空間也可以寫(xiě)/,在前端中寫(xiě)href = "/Action.action"即可;
    extends屬性:繼承一個(gè)指定包,,其中struts-default為必須繼承
<action>標(biāo)簽:配置action類
      name屬性決定action的訪問(wèn)資源名
      class屬性為Action的完整類名
      method屬性:指定調(diào)用action類中的哪個(gè)方法來(lái)處理請(qǐng)求
處理異常: <global-exception-mappings>
  <exception-mapping>中的result屬性為設(shè)置異常處理標(biāo)識(shí),要與<result>標(biāo)簽中的name屬性相同, 
  exception屬性為具體出現(xiàn)的錯(cuò)誤名稱
<result> 標(biāo)簽:處理結(jié)果配置
    name屬性:標(biāo)識(shí)結(jié)果處理的名稱,一般與action的返回值相對(duì)應(yīng),也可處理異常返回結(jié)果
    type屬性:指定調(diào)用哪個(gè)result類來(lái)處理結(jié)果,默認(rèn)為轉(zhuǎn)發(fā)
          標(biāo)簽體:跳轉(zhuǎn)到哪個(gè)頁(yè)面或action
 引用寫(xiě)在具體包下的Struts.xml文件 
    <include file="cn/action/struts.xml"></include>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
  <struts>
  <!-- 可以在src中的Struts.xml中直接配置action -->
  <constant name="struts.devMode" value="true"></constant>
    <package name="LoginAction" namespace="/" extends="struts-default">
    
    <global-exception-mappings>
       <exception-mapping result="error" exception="java.lang.RuntimeException"></exception-mapping>
    </global-exception-mappings>
     <action name="LoginAction" class="cn.action.LoginAction" method="login">
      <result name="huanying">/index.html</result>
        <result name="error">/login.jsp</result>
     </action>
     </package>
     
      <!-- 引用寫(xiě)在具體包下的Struts.xml文件 -->
    <include file="cn/action/struts.xml"></include>
  </struts>
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容