多多色-多人伦交性欧美在线观看-多人伦精品一区二区三区视频-多色视频-免费黄色视屏网站-免费黄色在线

國內最全IT社區平臺 聯系我們 | 收藏本站
阿里云優惠2
您當前位置:首頁 > php開源 > php教程 > Struts2入門詳解

Struts2入門詳解

來源:程序員人生   發布時間:2016-06-07 08:14:02 閱讀次數:2420次

如何搭建Struts2項目

導入相干架包

編寫web.xml,配置strus2過濾器

<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>

編寫Struts2配置文件struts.xml

<?xml version="1.0" encoding="UTF⑻" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts⑵.3.dtd"> <struts> <package name="default" namespace="/user" extends="struts-default"> <action name="regist" class="cn.itcast.action.RegistAction"> <result name="input">/success.jsp</result> </action> </package> </struts>

訪問路徑 /user/regist.action
name 包名稱,在struts2的配置文件文件中 包名不能重復 ,name其實不是真正包名,只是為了管理Action
namespace 和 action的name屬性,決定 Action的訪問路徑 (以/開始 )
extends 繼承哪一個包,通常開發中繼承 struts-default 包 (struts-default包在 struts-default.xml定義 )
繼承struts-default包后,可使用 包中定義攔截器和結果類型
action元素配置默許值
package 的namespace 默許值‘’‘’
action 的class 默許值 ActionSupport 類
result 的 name 默許值 success

默許Action 和 Action的默許處理類

1) 默許Action , 解決客戶端訪問Action不存在的問題 ,客戶端訪問Action, Action找不到,默許Action 就會履行

2) 默許處理類 ,客戶端訪問Action,已找到匹配元素,但是元素沒有class屬性,履行默許處理類

* 在struts-default.xml 配置默許處理類 ActionSupport

Struts2的常量配置

1) struts2 默許常量 在 default.properties 中配置
2) 開發者自定義常量

struts.xml 格式 : <constant name="struts.devMode" value="true" /> struts.properties 格式 : struts.devMode = true web.xml 格式 : <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> <init-param> <param-name>struts.devMode</param-name> <param-value>true</param-value> </init-param> </filter>

3) 經常使用常量

<constant name="struts.i18n.encoding" value="UTF⑻"/>  ----- 相當于request.setCharacterEncoding("UTF⑻"); 解決post要求亂碼 
<constant name="struts.action.extension" value="action"/>  --- 訪問struts2框架Action訪問路徑 擴大名 (要求)
struts.action.extension=action, 默許以.action結尾擴大名 和 不寫擴大名 都會分發給 Action
<constant name="struts.serve.static.browserCache" value="false"/> false不緩存,true閱讀器會緩存靜態內容,產品環境設置true、開發環境設置false 
<constant name="struts.devMode" value="true" />  提供詳細報錯頁面,修改struts.xml后不需要重啟服務器 

Action

Action書寫的的3種格式

第1種

Action可以是 POJO ((PlainOldJavaObjects)簡單的Java對象) —- 不需要繼承任何父類,實現任何接口
* struts2框架 讀取struts.xml 取得 完全Action類名
* obj = Class.forName(“完全類名”).newInstance();
* Method m = Class.forName(“完全類名”).getMethod(“execute”); m.invoke(obj); 通過反射 履行 execute方法

第2種

編寫Action 實現Action接口
Action接口中,定義默許5種 邏輯視圖名稱
public static final String SUCCESS = “success”; // 數據處理成功 (成功頁面)
public static final String NONE = “none”; // 頁面不跳轉 return null; 效果1樣
public static final String ERROR = “error”; // 數據處理發送毛病 (毛病頁面)
public static final String INPUT = “input”; // 用戶輸入數據有誤,通經常使用于表單數據校驗 (輸入頁面)
public static final String LOGIN = “login”; // 主要權限認證 (登陸頁面)
5種邏輯視圖,解決Action處理數據后,跳轉頁面

第3種

編寫Action 繼承ActionSupport (推薦)
在Action中使用 表單校驗、毛病信息設置、讀取國際化信息 3個功能

Action的配置method(通配符)

1) 在配置 元素時,沒有指定method屬性, 默許履行 Action類中 execute方法
2)使用通配符* ,簡化struts.xml配置

<a href="${pageContext.request.contextPath }/user/customer_add.action">添加客戶</a>
<a href="${pageContext.request.contextPath }/user/customer_del.action">刪除客戶</a>

struts.xml
<action name="customer_*" class="cn.itcast.struts2.demo4.CustomerAction" method="{1}"></action>   ---  {1}就是第1個* 匹配內容

動態方法調用

訪問Action中指定方法,不進行配置
1) 在工程中使用 動態方法調用 ,必須保證 struts.enable.DynamicMethodInvocation = true 常量值 為true
2) 在action的訪問路徑 中 使用 “!方法名”

頁面
<a href="${pageContext.request.contextPath }/user/product!add.action">添加商品</a>
配置
<action name="product" class="cn.itcast.struts2.demo4.ProductAction"></action>
履行 ProductAction 中的 add方法

Action訪問Servlet API

1、 在Action 中解耦合方式 間接訪問 Servlet API ——— 使用 ActionContext 對象

在struts2 中 Action API 已與 Servlet API 解耦合 (沒有依賴關系 )
* Servlet API 常見操作 : 表單提交要求參數獲得,向request、session、application3個范圍存取數據

actionContext = ActionContext.getContext();
1) actionContext.getParameters(); 取得所有要求參數Map集合
2) actionContext.put(“company”, “傳智播客”); / actionContext.get(“company”) 對request范圍存取數據
3) actionContext.getSession(); 取得session數據Map,對Session范圍存取數據
4) actionContext.getApplication(); 取得ServletContext數據Map,對利用訪問存取數據

2、 使用接口注入的方式,操作Servlet API (耦合)

1.要求action類必須實現提定接口。
ServletContextAware : 注入ServletContext對象
ServletRequestAware :注入 request對象
ServletResponseAware : 注入response對象

2.重定接口中的方法。
private HttpServletRequest request;
3.聲明1個web對象,使用接口中的方法的參數對聲明的web對象賦值.

public void setServletRequest(HttpServletRequest request) {
    this.request = request;
}

3、 在Action中直接通過 ServletActionContext 取得Servlet API

ServletActionContext.getRequest() : 取得request對象 (session)
ServletActionContext.getResponse() : 取得response 對象
ServletActionContext.getServletContext() : 取得ServletContext對象
ServletActionContext.getPageContext().getSession(); //獲得session等對象

Action處理要求參數

第1種 :Action 本身作為model對象,通過成員setter封裝 (屬性驅動 )

頁面: 用戶名 <input type="text" name="username" /> Action : public class RegistAction1 extends ActionSupport { private String username; public void setUsername(String username) { this.username = username; } }

第2種 :創建獨立model對象,頁面通過ognl表達式封裝 (屬性驅動)

頁面: 用戶名 <input type="text" name="user.username" />----- 基于OGNL表達式的寫法 Action: public class RegistAction2 extends ActionSupport { private User user; public void setUser(User user) { this.user = user; } public User getUser() { return user; } }

使用ModelDriven接口,對要求數據進行封裝 (模型驅動 ) —– 主流

頁面: 用戶名 <input type="text" name="username" /> <br/> Action : public class RegistAction3 extends ActionSupport implements ModelDriven<User> { private User user = new User(); // 必須手動實例化 public User getModel() { return user; } }

封裝數據到Collection和Map

1) 封裝數據到Collection 對象
頁面:

產品名稱 <input type="text" name="products[0].name" /><br/> Action : public class ProductAction extends ActionSupport { private List<Product> products; public List<Product> getProducts() { return products; } public void setProducts(List<Product> products) { this.products = products; } }

2) 封裝數據到Map 對象
頁面:

產品名稱 <input type="text" name="map['one'].name" /><br/> ======= one是map的鍵值 Action : public class ProductAction2 extends ActionSupport { private Map<String, Product> map; public Map<String, Product> getMap() { return map; } public void setMap(Map<String, Product> map) { this.map = map; } }

要求參數校驗

手工代碼校驗要求參數

步驟1: 封裝數據
步驟2: 實現校驗Action ,必須繼承ActionSupport 類
步驟3: 覆蓋validate方法,完成對Action的業務方法 數據校驗通過代碼邏輯判斷參數是不是有效,如果參數非法 , this.addFieldError (ActionSupport提供)workflow攔截器 跳轉回 input頁面
步驟4: 在jsp中 通過 s:fieldError 顯示毛病信息
validate方法會對Action中所有業務方法進行校驗,如果只想校驗某1個方法 : validate方法名()

Xml配置方式數據校驗

位置:xml文件要與action類在同1個包下
名稱:action類名-validation.xml(針對某個方法效驗UserAction-regist-validation.xml)

<?xml version="1.0" encoding="UTF⑻"?> <!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0.3//EN" "http://struts.apache.org/dtds/xwork-validator⑴.0.3.dtd"> <validators> <!-- 對username屬性進行校驗 --> <field name="username"> <!-- 指定username不能為空 --> <field-validator type="requiredstring"> <!-- 毛病信息 --> <message>用戶名不能為空--------</message> </field-validator> <!-- 長度校驗,規定用戶名必須在6⑴0位之間 --> <field-validator type="stringlength"> <param name="maxLength">10</param> <param name="minLength">6</param> <message>用戶名必須在${minLength}-${maxLength}位之間</message> </field-validator> </field> <!-- 對age進行校驗,規定年齡必須在10⑷0之間 --> <field name="age"> <field-validator type="int"> <param name="min">10</param> <param name="max">40</param> <message>年齡必須在${min}--${max}之間</message> </field-validator> </field> <!-- 對birthday進行校驗 --> <field name="birthday"> <field-validator type="date"> <param name="min">1974-01-01</param> <param name="max">2004⑴2⑶1</param> <message>生日必須在${min}年到${max}年之間</message> </field-validator> </field> <!-- 校驗郵箱 --> <field name="email"> <field-validator type="email"> <message>郵箱格式不正確</message> </field-validator> </field> <!-- url校驗 --> <field name="url"> <field-validator type="url"> <message>url不能這空,類似于http://www.baidu.com</message> </field-validator> </field> <!-- 使用正則 --> <field name="telphone"> <field-validator type="regex"> <param name="regexExpression"><![CDATA[^135[0⑼]{8}$]]></param> <message>電話號碼必須是135xxxxxxxx</message> </field-validator> </field> <field name="repassword"> <field-validator type="fieldexpression"> <param name="expression"><![CDATA[(password==repassword)]]></param> <message>兩次密碼輸入不1致</message> </field-validator> </field> </validators>

內建校驗器
* required (必填校驗器,要求被校驗的屬性值不能為null)
* requiredstring (必填字符串校驗器,要求被校驗的屬性值不能為null,并且長度大于0,默許情況下會對字符串去前后空格)
* stringlength (字符串長度校驗器,要求被校驗的屬性值必須在指定的范圍內,否則校驗失敗,minLength參數指定最小長度,maxLength參數指定最大長度,trim參數指定校驗field之前是不是去除字符串前后的空格)
* regex (正則表達式校驗器,檢查被校驗的屬性值是不是匹配1個正則表達式,expression參數指定正則表達式,caseSensitive參數指定進行正則表達式匹配時,是不是辨別大小寫,默許值為true)
* int(整數校驗器,要求field的整數值必須在指定范圍內,min指定最小值,max指定最大值)
* double(雙精度浮點數校驗器,要求field的雙精度浮點數必須在指定范圍內,min指定最小值,max指定最大值)
* fieldexpression (字段OGNL表達式校驗器,要求field滿足1個ognl表達式,expression參數指定ognl表達式,該邏輯表達式基于ValueStack進行求值,返回true時校驗通過,否則不通過)
* email(郵件地址校驗器,要求如果被校驗的屬性值非空,則必須是合法的郵件地址)
* url(網址校驗器,要求如果被校驗的屬性值非空,則必須是合法的url地址)
* date(日期校驗器,要求field的日期值必須在指定范圍內,min指定最小值,max指定最大值)

Result結果類型;

Action處理要求后, 返回字符串(邏輯視圖名), 需要在struts.xml 提供 元素定義結果頁面
1、 局部結果頁面 和 全局結果頁面

<action name="result" class="cn.itcast.struts2.demo6.ResultAction"> <!-- 局部結果 當前Action使用 --> <result name="success">/demo6/result.jsp</result> </action> <global-results> <!-- 全局結果 當前包中 所有Action都可以用--> <result name="success">/demo6/result.jsp</result> </global-results>

2、 結果頁面跳轉類型
result標簽
1.name 與action中的method的返回值匹配,進行跳轉.
2.type 作用:是用于定義跳轉方式

dispatcher:它代表的是要求轉發,也是默許值。它1般用于從action跳轉到頁面。
chain:它也相當于要求轉發。它1般情況下用于從1個action跳轉到另外一個action。

<!--hello是1個Action的name-->
<result name="success" type="chain">hello</result>

redirect:它代表的是重定向 它1般用于從action跳轉到頁面
redirectAction: 它代表的是重定向 它1般用于從action跳轉另外一個action。

<result name="success" type="redirectAction">hello</result>

stream:代表的是服務器端返回的是1個流,1般用于下載。

在jsp中顯示毛病信息

<s:fieldError/> <s:fielderror fieldName="">展現特定名稱的毛病信息.

Struts2國際化

資源文件編寫

properties文件命名 : 基本名稱語言(小寫)國家(大寫).properties
編寫3個property文件

message.properties

name=tom

messages_zh_CN.properties //中國中文

name=湯姆

messages_en_US.properties //美國英文

name=tom

資源文件作用域

1.針對action類
位置:與action類在同1個包下.
名稱:ActionClassName.properties.
這個配置文件只對當前action有效。

2.針對package下所有action
位置:在指定的包下
名稱:package.properties

怎樣使用

1.在action類中使用
條件:action類要繼承ActionSupport類。
getText(String name)就能夠獲得配置文件中對應名稱的值。

2.在validation.xml文件中使用

<message key="名稱"/>

3.在jsp頁面上使用

s:text name=”名稱” 如果沒有使用s:i18n name=”“來指定,會從全局配置文件中獲得。
如果要從某1個配置文件中獲得,通過name屬性來指定, 包名.配置文件名稱 .

<s:i18n name="cn.itcast.action.package"> <s:text name="nameerror"/> </s:i18n>

在struts2中國際化配置文件中使用動態文本

1.action中怎樣使用

xxxx.property

msg=hello world  {0}

action

this.getText("msg",new String[]{"tom"})

結果就是 hello world tom

2.jsp頁面上怎樣使用

xxxx.property
msg=hello world {0}

<s:i18n name="cn.itcast.action.I18nDemo1Action">
    <s:text name="msg">
        <s:param>張3</s:param>
    </s:text>
</s:i18n>

結果就是 hello world 張3

Struts2攔截器

struts2中在struts-default.xml文件中聲明了所有的攔截器。
而struts2框架默許使用的是defaultStack這個攔截器棧。
在這個攔截器棧中使用了18個攔截器。簡單說,struts2框架
在默許情況下,加載了18個攔截器。
注意:只要顯示聲明使用了1個攔截器。那末默許的攔截器就不在加載。

經常使用struts2 攔截器

<interceptor-ref name="modelDriven"/> 模型驅動
<interceptor-ref name="fileUpload"/> 文件上傳
<interceptor-ref name="params"> 參數解析封裝 
<interceptor-ref name="conversionError"/> 類型轉換毛病
<interceptor-ref name="validation"> 要求參數校驗
<interceptor-ref name="workflow"> 攔截跳轉 input 視圖

自定義攔截器

struts.xml

<interceptors> <interceptor name="my" class="cn.itcast.intercept.MyInterceptor"> </interceptor> <interceptor name="bookInterceptor" class="cn.itcast.intercept.BookInterceptor"> <param name="includeMethods">add,update,delete</param> </interceptor> <interceptor-stack name="myStack"> <interceptor-ref name="bookInterceptor"></interceptor-ref> <interceptor-ref name="defaultStack" /> </interceptor-stack> </interceptors> <action name="demo1" class="cn.itcast.action.Demo1Action"> <result name="login">/login.jsp</result> <!-- <interceptor-ref name="my" /> <interceptor-ref name="defaultStack"/> --> <interceptor-ref name="myStack" /> </action>

action

public class BookInterceptor extends MethodFilterInterceptor { @Override protected String doIntercept(ActionInvocation invocation) throws Exception { // 1.得到session中的user User user = (User) ServletActionContext.getRequest().getSession().getAttribute("user"); if (user == null) { BookAction action = (BookAction) invocation.getAction(); // 得到當前攔截的action對象。 action.addActionError("權限不足,請先登錄");// 存儲毛病信息 return Action.LOGIN; } return invocation.invoke(); } }
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈
程序員人生
------分隔線----------------------------
分享到:
------分隔線----------------------------
關閉
程序員人生
主站蜘蛛池模板: 一级毛片视频在线 | 亚洲视频网址 | 亚洲精品永久www忘忧草 | 亚洲女人影院想要爱 | 亚洲人在线观看 | 武则天一级淫片免费放 | 武则天一级淫片免费 | 亚洲天堂欧美 | 亚洲不卡| 欧美18性欧美丶黑吊 | 日本一区二区精品88 | 国产成人一区二区在线不卡 | 日本欧美一区二区三区高清 | 精品亚洲77777www | 高清欧美色欧美综合网站 | s级毛片 | 视频一区二区国产无限在线观看 | 欧美一级在线 | 亚洲精品第一综合99久久 | 亚洲一本 | 日韩在线影视 | 国产精品一区二区三区免费视频 | 成年人在线观看免费视频 | 亚洲欧美久久 | 91精品综合国产在线观看 | 91久久大香伊蕉在人线 | 国产成人精品日本亚洲专一区 | 欧美 日韩 亚洲另类专区 | 国产精品v | 欧美a一片xxxx片 | 视频在线免费观看 | 亚洲精品不卡久久久久久 | 国产在线日韩在线 | 亚拍精品一区二区三区 | 伊人伊人影院 | 欧美亚洲一区 | 中文字幕亚洲色图 | 国产精品亚洲综合一区 | 亚洲自拍成人 | 久久永久视频 | 亚洲另类春色校园小说 |