%lt%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<html>
<head>
<title>Spring MVC Form<itle>
</head>
<body>
<form:form action="/submitForm" method="post" modelAttribute="userForm">
<label for="username">Username:<label>
<form:input path="username" id="username" />
<br/>
<label for="password">Password:<label>
<form:password path="password" id="password" />
<br/>
<input type="submit" value="Submit" />
<form:form>
</body>
</html>
@Controller
public class FormController {
@GetMapping("/showForm")
public String showForm(Model model) {
model.addAttribute("userForm", new UserForm());
return "form-page";
}
@PostMapping("/submitForm")
public String submitForm(@ModelAttribute("userForm") UserForm userForm) {
// 处理表单提交逻辑
return "result-page";
}
}
public class UserForm {
private String username;
private String password;
// getter和setter方法...
}
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
public class UserValidator implements Validator {
@Override
public boolean supports(Class> clazz) {
return User.class.equals(clazz);
}
@Override
public void validate(Object target, Errors errors) {
User user = (User) target;
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "username", "NotEmpty");
if (user.getUsername().length() < 5 || user.getUsername().length() > 20) {
errors.rejectValue("username", "Size.userForm.username");
}
// 其他验证逻辑...
}
}
@Controller
public class UserController {
@Autowired
private UserValidator userValidator;
@InitBinder
protected void initBinder(WebDataBinder binder) {
binder.addValidators(userValidator);
}
@PostMapping("/submitForm")
public String submitForm(@ModelAttribute("userForm") @Validated User user, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return "form-page";
}
// 处理表单提交逻辑
return "result-page";
}
}
public class User {
@Size(min = 5, max = 20, message = "Username must be between 5 and 20 characters")
private String username;
// 其他属性和验证注解...
}
@Controller
public class UserController {
@PostMapping("/submitForm")
public String submitForm(@ModelAttribute("userForm") @Valid User user, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return "form-page";
}
// 处理表单提交逻辑
return "result-page";
}
}