程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> Struts validate驗證的具體實現

Struts validate驗證的具體實現

編輯:關於JAVA

Struts validate驗證

1. ActionErrors和ActionError都是ActionMessages的子類,ActionError存放在ActionErrors 中, ActionError對象中的參數為配置文件中配置的相應的值,若配置文件中沒有配置或配置文件不適合都不 能用< htnl:errors property=""/>輸出。

2.錯誤信息添加用

ActionErrors errors=new ActionErrors();

errors.add("error_key",new ActionError("配置文件中的相應的值"))

注解:void add(java.lang.String property,ActionError error)

在jsp頁面中顯示錯誤:

3.在Action中使用ActionMessages 他有兩個add方法:

他有兩個add方法:

void add(ActionMessages  message)
 Adds the meesage from the given ActionMessage object  to tjis set of meesage
void add(java.lang.String property,ActionMessage message)
            Add message to the set of message for the specifiled 

property.

錯誤信息添加使用errors.add("error_key",new ActionMessage("errors.loginerror"))

另外要調用this.saveMessages(request,errors)方法;

這是org.apache.structs.action.Action中 的方法,要用到的大概有兩個:

1.saveErrors(少用)

protected void saveErrors(java.servlet,http.HttoServletRequest request,ActionErrors errors)

Save the specifiled error message keys into the appropriate request attribute for use by the<html:errors>

tag,if any message are required.Otherwise,ensure that the request attribute is not created.

2.saveMessage(常用)

protect void saveMessage(javax.Servlet.http.HttpServletRequest request,ActionMessages  messages)

Save the specified message keys into the appropriate request attribute for use by the<html:message>tag{

if messages="true"    is set},if any message are required,Otherwise,ensure that the request attribute  is not

created.

ActionErrors actionMessages ,ActionMessage ActionMessage是繼承關系,父類在前,子類在後

if (!loadForm.getUsername().equals("123"))
{ ActionMessages error = new ActionMessages();
error.add("username", new ActionMessage("error.username"));
saveErrors(request, error);
return mapping.findForward("S1"); }
if (!loadForm.getPassword().equals("abc")) {
ActionMessages error = new ActionMessages();
error.add("password", new ActionMessage("error.password"));
saveErrors(request, error);
return mapping.findForward("S1"); }
return mapping.findForward("S1");
error.username=<font color="red">\u5e10\u53f7\u9519</font>
error.password=<font color="red">\u5bc6\u7801\u9519</font>
error.up=<font color="red">\u5e10\u53f7\u6216\u5bc6\u7801\u4e0d\u80fd\u7a7a</font>

FORM裡面

public ActionErrors validate(ActionMapping mapping,
  HttpServletRequest request) {
 ActionErrors errors = new ActionErrors();
if (null == username.trim() || null == password.trim()||username.length()<3

||password.length()<2) {

  errors.add("username", new ActionMessage("error.up"));
  System.out.println(errors);
  return errors;
 }
 return null;
}
native2ascii 來處理中文漢字
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved