Struts2學習筆記(4)-萬用字元的使用_java

來源:互聯網
上載者:User

萬用字元是在struts2配置中非常常用的一種配置方式,在程式開發過程中要遵循“約定優於配置”的原則,在這種原則下,約定的結果如果比較合適的話,就會大大減少配置的數量,使得配置變得非常簡單,方便。

下面以例子來做下說明:

1、由如此的一個struts.xml設定檔:

複製代碼 代碼如下:
<?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> 
    <constant name="struts.devMode" value="true" /> 
    <package name="actions" extends="struts-default" namespace="/actions"> 
        <action name="Student*" class="com.bjsxt.struts2.action.StudentAction" method="{1}"> 
            <result>/Student{1}_success.jsp</result> 
        </action> 
         
        <action name="*_*" class="com.bjsxt.struts2.action.{1}Action" method="{2}"> 
            <result>/{1}_{2}_success.jsp</result> 
            <!-- {0}_success.jsp --> 
        </action> 
    </package> 
</struts>

第一個action使用了一種單個“ * ”的配置方式,它的method="{1}",這個{1}代表的是前面的name屬性中的第一個*,對比第二個action,{2}代表的是前面name屬性中的第2個*;類似的在第一個action中的result中的{1}也是代表name屬性中的第一個*,同樣類比第二個result。

2、假如有一個index.jsp檔案

複製代碼 代碼如下:
<?xml version="1.0" encoding="GB18030" ?> 
<%@ page language="java" contentType="text/html; charset=GB18030" 
    pageEncoding="GB18030"%> 
 
<% String context = request.getContextPath(); %> 
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=GB18030" /> 
<title>Insert title here</title> 
</head> 
<body> 
使用萬用字元,將配置量降到最低<br /> 
<a href="<%=context %>/actions/Studentadd">新增學生</a> 
<a href="<%=context %>/actions/Studentdelete">刪除學生</a> 
<br /> 
不過,一定要遵守"約定優於配置"的原則 
<br /> 
<a href="<%=context %>/actions/Teacher_add">添加老師</a> 
<a href="<%=context %>/actions/Teacher_delete">刪除老師</a> 
<a href="<%=context %>/actions/Course_add">添加課程</a> 
<a href="<%=context %>/actions/Course_delete">刪除課程</a> 
     
</body> 
</html>

那麼根據萬用字元的原理,對於第一個<a></a>,它的指向是StudentAction類中的add方法,則會調用Studentadd_success.jsp檔案。同理對於第三個<a></a>則會指向TeacherAction的add方法,調用Teacher_add_success.jsp檔案。

萬用字元的使用使得struts2的配置變得非常簡單,它也有自己的原則,即:準確性匹配,越準確則更容易匹配到,例如當由兩個action的name都可以匹配到時,它會自動選擇更精確的匹配(此時的更精確值得是不含有萬用字元的情況),在都含有萬用字元的情況下,好像是哪個在前面哪個更先匹配!

以上就是Struts2的萬用字元的使用的全部內容,希望能給大家一個參考,也希望大家多多支援雲棲社區。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.