Struts2基於XML配置方式實現對Action方法進行校正

來源:互聯網
上載者:User

使用XML對Action方法進行校正方式有兩種,一種是對Action的所有方法進行校正,另一種是對Action指定方法進行校正.

對Action的所有方法進行校正:

步驟:

1.建立Action需要繼承ActionSupport

2.提供校正的xml檔案,該檔案和action放在同一個包下

校正檔案的取名格式為:PersonAction-validation.xml,其中PersonAction為action的簡單類名,-valication為固定寫法

樣本:

Action:

public class PersonAction extends ActionSupport{private String username;private String mobile;public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getMobile() {return mobile;}public void setMobile(String mobile) {this.mobile = mobile;}public String update(){ActionContext.getContext().put("message", "更新成功");return "message";}public String save(){ActionContext.getContext().put("message", "儲存成功");return "message";}}

校正的xml檔案:

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.3//EN" "http://www.opensymphony.com/xwork/xwork-validator-1.0.3.dtd"> <validators>    <field name="username">        <field-validator type="requiredstring">            <param name="trim">true</param>            <message>使用者名稱不可為空!</message>        </field-validator>    </field>    <field name="mobile">        <field-validator type="requiredstring">            <message>手機號不可為空!</message>        </field-validator>        <field-validator type="regex">     <param name="expression"><![CDATA[^1[358]\d{9}$]]></param>     <message>手機號格式不正確!</message></field-validator>    </field></validators>

通過Struts2標籤庫列印校正資訊:

<%@ taglib uri="/struts-tags" prefix="s"%><s:fielderror/>

對Action指定方法進行校正:

要對指定的Action方法進行校正必須指明要校正的方法,指明校正的方法需要修改校正的檔案名稱,比如”PersonAction-manage_update-validation.xml“,

PersonAction為要校正的Action;

manage_update指定Action中校正的方法如下struts.xml的 action name

validation為規定名稱。

<struts>      <package name="person" namespace="/person" extends="struts-default">        <action name="manage_*" class="cn.itcast.action.PersonAction" method="{1}">        <result name="input">/index.jsp</result>        <result name="message">/WEB-INF/page/message.jsp</result>        </action> </package></struts>

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.