1 18 19 package org.apache.struts.validator; 20 21 import java.io.Serializable ; 22 import java.util.Map ; 23 24 import javax.servlet.ServletContext ; 25 import javax.servlet.http.HttpServletRequest ; 26 27 import org.apache.commons.beanutils.DynaBean; 28 import org.apache.commons.logging.Log; 29 import org.apache.commons.logging.LogFactory; 30 import org.apache.commons.validator.Validator; 31 import org.apache.commons.validator.ValidatorException; 32 import org.apache.commons.validator.ValidatorResults; 33 import org.apache.struts.action.ActionErrors; 34 import org.apache.struts.action.ActionMapping; 35 import org.apache.struts.action.DynaActionForm; 36 37 51 public class DynaValidatorForm extends DynaActionForm implements DynaBean, Serializable { 52 53 56 private static Log log = LogFactory.getLog(DynaValidatorForm.class); 57 58 62 protected ValidatorResults validatorResults = null; 63 64 67 protected int page = 0; 68 69 73 public int getPage() { 74 return page; 75 } 76 77 81 public void setPage(int page) { 82 this.page = page; 83 } 84 85 96 public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) { 97 this.setPageFromDynaProperty(); 98 99 ServletContext application = getServlet().getServletContext(); 100 ActionErrors errors = new ActionErrors(); 101 102 String validationKey = getValidationKey(mapping, request); 103 104 Validator validator = Resources.initValidator(validationKey, 105 this, 106 application, request, 107 errors, page); 108 109 try { 110 validatorResults = validator.validate(); 111 } catch (ValidatorException e) { 112 log.error(e.getMessage(), e); 113 } 114 115 return errors; 116 } 117 118 125 public String getValidationKey(ActionMapping mapping, 126 HttpServletRequest request) { 127 128 return mapping.getAttribute(); 129 } 130 131 136 protected void setPageFromDynaProperty() { 137 Map props = this.getMap(); 138 if (props.containsKey("page")) { 139 Integer p = null; 140 try { 141 p = (Integer )props.get("page"); 142 } catch (ClassCastException e) { 143 log.error("Dyna 'page' property must be of type java.lang.Integer.", e); 144 throw e; 145 } 146 if (p == null) { 147 throw new NullPointerException ("Dyna 'page' property must not be null. " + 148 " Either provide an initial value or set 'convertNull' to false. "); 149 } 150 this.page = p.intValue(); 151 } 152 } 153 154 160 public void reset(ActionMapping mapping, HttpServletRequest request) { 161 super.reset(mapping, request); 162 page = 0; 163 validatorResults = null; 164 } 165 166 171 public ValidatorResults getValidatorResults() { 172 return validatorResults; 173 } 174 175 180 public void setValidatorResults(ValidatorResults validatorResults) { 181 this.validatorResults = validatorResults; 182 } 183 184 191 public Map getResultValueMap() { 192 return (validatorResults != null ? validatorResults.getResultValueMap() : null); 193 } 194 195 } 196 197 | Popular Tags |