Struts2資料校正,struts2校正

來源:互聯網
上載者:User

Struts2資料校正,struts2校正

 一.為什麼要進行資料校正 

      對於一個web應用而言,所有的應用資料都是通過瀏覽器收集的,使用者的輸入資訊是非常複雜的,對於一些使用者操作不熟練,輸入出錯,等網路傳輸不穩定,這些都有可能導致異常輸入。

    異常的輸入,輕則導致系統非正常中斷,重則導致系統崩潰,應用程式必須能正常處理表現層接收的異常資料,通常的做法是遇到非法資料,應用程式將相應的給出使用者提示,提示使用者必須輸入要求的資料,也就是將那些異常輸入過濾掉,我們說對異常資料的過濾就是資料校正。

    二.如何?資料校正

    我們可以讓一個自訂類去繼承自一個ActionSupport類,這個類是一個預設的的Action實作類別,他的完全限定名com.opensymphony.xwork2.ActionSupport.這個類中提供了很多的預設方法,包括擷取國際化資訊的方法,資料校正的方法,以及預設處理使用者請求的方法等,由於ActionSupport類是Struts2預設的實作類別,所以如果在struts.xml中的Action配置中省略了class屬性,則代表訪問ActionSupport類,其execute()方法直接返回SUCCESS,同時ActionSupport類還增加了對驗證,本地化的支援。

login.jsp

 <div>    <!-- 輸出校正資訊  注意標籤的名稱要與方法的名稱相對應-->    <s:fielderror fieldName="errorname"/>     <s:fielderror fieldName="errorpwd"/>    </div>     <form action="Login.action" method="post" >         使用者名稱:<input type="text" name="username"/>         密碼:<input type="text" name="userpwd"/>         <input type="submit" value="登入">   </form>

 

LoginAction類

public class LoginAction extends ActionSupport{     private String username;     private String userpwd;                 @Override        public void validate() {            if(username.length()==0){
   //添加資訊內容 addFieldError("errorname", "使用者名稱不可為空"); } if(userpwd.length()==0) { addFieldError("errorpwd","密碼不可為空"); } } @Override public String execute() throws Exception { if(username.equals("123")&&userpwd.equals("123")){ //通過解耦合的方式擷取到一個Map Map<String,Object> map=ActionContext.getContext().getSession(); //如果使用者使用者名稱和密碼輸入正確,把值儲存到集合中,也就是把值放到session中 map.put("name", username); return SUCCESS; }else{ return INPUT; } }

 

struts.xml

<struts>    <!-- 設定檔中只要添加以下配置,那麼以後修改設定檔不用重啟tomcat -->    <constant name="struts.devMode" value="true"/>       <package name="default" namespace="/" extends="struts-default">        <action name="Login" class="cn.action.LoginAction">           <result name="success">           Login/scuess.jsp           </result>           <result name="input">           Login/login.jsp           </result>        </action>      </package></struts>

如何避免這種讓Struts2架構自動產生的標籤

我們可以在struts.xml中配置這個節點:

<!--設定使用者介面主題,預設值為XHTML風格--> 
<constant name="struts.ui.theme" value="simple"></constant>

通過配置struts.xml的方式,來改變一些常量值,來控制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.