开发Spring MVC应用程序(3-2)

来源:互联网 发布:手机号收集软件 编辑:程序博客网 时间:2024/06/05 23:02

22)增加表单

l         下面增加一个允许用户输入百分值的表单。由于表单中使用了Spring的标记,所以将dist/spring.tld导入到springapp/WEB-INF目录下,并在web.xml中增加<taglib>条目

  <taglib>
    <taglib-uri>/spring</taglib-uri>
    <taglib-location>/WEB-INF/spring.tld</taglib-location>
  </taglib>

l         在表单页面priceincrease.jsp中,定义了包含一个输入增加百分比的文本域和提交按钮的表单

<%@ include file="/WEB-INF/jsp/include.jsp" %>
<%@ taglib prefix="spring" uri="/spring" %>
 
<html>
<head><title><fmt:message key="title"/></title></head>
<body>
<h1><fmt:message key="priceincrease.heading"/></h1>
<form method="post">
  <table width="95%" bgcolor="f8f8ff" border="0" cellspacing="0" cellpadding="5">
    <tr>
      <td alignment="right" width="20%">Increase (%):</td>
      <spring:bind path="priceIncrease.percentage">
        <td width="20%">
          <input type="text" name="percentage" value="<c:out value="${status.value}"/>">
        </td>
        <td width="60%">
          <font color="red"><c:out value="${status.errorMessage}"/></font>
        </td>
      </spring:bind>
    </tr>
  </table>
  <br>
  <spring:hasBindErrors name="priceIncrease">
    <b>Please fix all errors!</b>
  </spring:hasBindErrors>
  <br><br>
  <input type="submit" alignment="center" value="Execute">
</form>
<a href="<c:url value="hello.htm"/>">Home</a>
</body>
</html>

l         <spring:bind>绑定文本域到Command对象(后面介绍)的属性(由path属性指定),status.value变量表示绑定属性的值,status.errorMessage变量表示验证错误时返回的错误信息

l         <spring:hasBindErrors>绑定错误到指定对象(由name属性指定)

l         Command对象是个简单的JavaBean,传递给验证器,如果验证通过,再传递给控制器

package bus;
 
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
 
public class PriceIncrease {
 
    /** Logger for this class and subclasses */
    protected final Log logger = LogFactory.getLog(getClass());
 
    private int percentage;
 
    public void setPercentage(int I) {
        percentage = I;
        logger.info(“Percentage set to “ + I);
    }
 
    public int getPercentage() {
        return percentage;
    }
 
}

l         用户提交表单时,表单的数据由Spring设置到Command对象中,并调用验证器进行数据有效性验证

package bus;
 
import org.springframework.validation.Validator;
import org.springframework.validation.Errors;
 
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
 
public class PriceIncreaseValidator implements Validator {
    private int DEFAULT_MIN_PERCENTAGE = 0;
    private int DEFAULT_MAX_PERCENTAGE = 50;
    private int minPercentage = DEFAULT_MIN_PERCENTAGE;
    private int maxPercentage = DEFAULT_MAX_PERCENTAGE;
 
    /** Logger for this class and subclasses */
    protected final Log logger = LogFactory.getLog(getClass());
 
    public boolean supports(Class clazz) {
        return clazz.equals(PriceIncrease.class);
    }
 
    public void validate(Object obj, Errors errors) {
        PriceIncrease pi = (PriceIncrease) obj;
        if (pi == null) {
            errors.rejectValue("percentage", "error.not-specified", null, "Value required.");
        }
        else {
            logger.info("Validating with " + pi + ": " + pi.getPercentage());
            if (pi.getPercentage() > maxPercentage) {
                errors.rejectValue("percentage", "error.too-high",
                    new Object[] {new Integer(maxPercentage)}, "Value too high.");
            }
            if (pi.getPercentage() <= minPercentage) {
                errors.rejectValue("percentage", "error.too-low",
                    new Object[] {new Integer(minPercentage)}, "Value too low.");
            }
        }
    }
 
    public void setMinPercentage(int i) {
        minPercentage = i;
    }
 
    public int getMinPercentage() {
        return minPercentage;
    }
 
    public void setMaxPercentage(int i) {
        maxPercentage = i;
    }
 
    public int getMaxPercentage() {
        return maxPercentage;
    }
 
}

l         验证器实现Validator接口,该接口有两个方法:

Ø         supports():决定指定类的对象是否能够验证

Ø         validate():实现验证对象,提供两个参数,一个是验证对象,一个是我们构建的包含与域属性相关的错误消息的Errors;错误消息可以使用前面介绍的status.errorMessage变量获取

l         Errors对象的rejectValue()方法用来弹出验证对象指定域属性的指定错误描述,它包含四个参数:属性名,消息key值(消息在属性文件中定义),消息参数(提供动态消息)和缺省消息