【SpringMVC】标签库:errors

@Controller
public class MyController {
	@RequestMapping(value="/result")
	public String registerForm(Model model){
		User user = new User();
		model.addAttribute("user", user);
		return "result";
	}

	@InitBinder
	public void initBinder(DataBinder binder){
		binder.setValidator(new UserValidator());
	}
	@RequestMapping(value="/click")
	public String register(@Validated User user,Errors errors){

		if(errors.hasFieldErrors())return "result";
		return "success";
	}
}
public class UserValidator implements Validator {
	@Override
	public boolean supports(Class<?> clazz) {
		return User.class.equals(clazz);
	}

	@Override
	public void validate(Object object, Errors errors) {// 验证 
		ValidationUtils.rejectIfEmpty(errors, "username", null, "用户名不能为空");
		ValidationUtils.rejectIfEmpty(errors, "sex", null, "性别不能为空");
		ValidationUtils.rejectIfEmpty(errors, "age", null, "年龄不能为空");
	}
}
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>

<body>

	<form:form modelAttribute="user" action="click" method="POST">
		<table>
			<tr>
				<td>姓名∶</td>
				<td><form:input path="username" /></td>
				<td><font color="red"><form:errors path="username" /></font></td>
			</tr>
			<tr>
				<td>性别∶</td>
				<td><form:input path="sex" /></td>
				<td><font color="red"><form:errors path="sex" /></font></td>
			</tr>
			<tr>
				<td>年龄∶</td>
				<td><form:input path="age" /></td>
				<td><font color="red"><form:errors path="age" /></font></td>
			</tr>
			<tr>
				<td><input type="submit" value="提交" /></td>
			</tr>
		</table>
	</form:form>

</body>
</html>
上一篇:Manifest merger failed with multiple errors, see logs 问题处理


下一篇:SQLLDR 优化