Spring MVC快速教程:表单验证 Spring MVC Fast Tutorial: Form Validation

What are we going to build?

User input validation for the new car form.

Validator

This Validator class will validate a Car: 'WEB-INF/src/springmvc/validator/CarValidator.java'

package springmvc.validator;
 
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
 
import springmvc.model.Car;
 
public class CarValidator implements Validator {
 
	public boolean supports(Class aClass) {
		return Car.class.equals(aClass);
	}
 
	public void validate(Object obj, Errors errors) {
		Car car = (Car) obj;
 
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "model", "field.required", "Required field");
 
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "price", "field.required", "Required field");
		if ( ! errors.hasFieldErrors("price")) {
			if (car.getPrice().intValue() == 0)
				errors.rejectValue("price", "not_zero", "Can't be free!");
		}		
	}
}
  • supports(): declare classes supported by this validator
  • To add an error these parameters are needed:
    • Car field name
    • error message key
    • default message if no message is not found for the key

View

Let's update the view 'jsp/carNew.jsp':

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
 
<html>
 
<head>
  <title>New Sponsor</title>
  <style>
    .error {
    	color: red;
    }
  </style>  
</head>
 
<body>
	<h1>New Car</h1>
 
	<form:form method="post">
 
		Brand<br />
		<form:select path="brand">
		   <form:options items="${brandList}" itemLabel="name" itemValue="id" />
		</form:select>
		<br /><br />
 
		Model <form:errors path="model" cssClass="error"/><br />
		<form:input path="model"/><br /><br />
 
		Price <form:errors path="price" cssClass="error"/><br />
		<form:input path="price"/><br /><br />
 
		<input type="submit" value="Submit">
 
	</form:form>
</body>
</html>

Configuration

We now declare the validator for the URL addCar.html in 'WEB-INF/springmvc-servlet.xml'

    <bean name="/new_car.html" class="springmvc.web.CarNewController">
        <property name="commandClass" value="springmvc.model.Car"/>
        <property name="formView" value="carNew"/>
        <property name="successView" value="list_cars.html"/>
		<property name="validator">
        	<bean class="springmvc.validator.CarValidator"/>
        </property>
    </bean>

Result

Build (ant) and relaunch Tomcat:http://localhost:8180/springmvc/new_car.html

We can check it's working by entering empty values:



from: http://jeromejaglale.com/doc/java/spring/form_validation

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值