分类
客户端验证:在客户端运行,不需要与服务器进行交互,不需要与数据库进行交互的验证,比如非空,格式,自定义的约束。
服务端验证:必须与数据库进行交互的验证,比如注册用户名是否可用,登陆用户名密码是否正确。
以前
客户端验证:主要用js完成。
服务端验证:java完成。
struts验证
- FormBean验证:功能与前面的客户端验证相同,主要是非空格式等。
- action验证:功能与前面的服务器段验证相同,主要是需要与数据库进行通信。
FormBean验证
- 重写FormBean的validate方法。
@Override public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) { ActionErrors errors = new ActionErrors(); if (userName == null || userName.equals("")) { //userNameEmpty 错误的别名 errors.add("userNameEmpty", new ActionMessage("input.empty", "xaygc UserName ")); } if (password == null || password.equals("")) { errors.add("passWordEmpty", new ActionMessage("input.empty", "xaygc Password ")); } return errors; }
在struts-config.xml中配置action节点的validate与input属性,validate表示是否调用formBean的validate方法,input是如果出错的话跳转的错误处理界面。注意:如果formBean重写的了validate方法并且action节点validate属性为true,那一定要添加input属性。 - 在界面使用<html:errors />或<html:errors property="userNameEmpty"/>显示错误信息。
- 虽然完成客户端验证功能,但需要与服务器交互。注意不同的区分标准。
加验证的流程
这里流程为追加,前期参见Struts运行流程
ActionBean验证
ActionMessages messages = new ActionMessages(); messages.add("loginError", new ActionMessage("login.error")); ///new ActionMessages().add("loginError", new ActionMessage("login.error")); super.saveErrors(request, messages); return mapping.getInputForward();
ActionBean验证主要做业务,需要与数据库交互,比如用户名是否可用,转账余额是否可用,出货余额等验证,formBean类似于以前的js验证。