代码来自Spring in action 165页
在pojo上加入注解,个人认为这样编写工作量相当大,而且对代码侵入比较高。
public class Spitter { private Long id; @NotNull @Size(min=5, max=16) private String username; @NotNull @Size(min=5, max=25) private String password; @NotNull @Size(min=2, max=30) private String firstName; @NotNull @Size(min=2, max=30) private String lastName; @NotNull @Email private String email; -------------------------------------------- //下面是setter和getter方法
在控制层进行验证
package spittr.web; import static org.springframework.web.bind.annotation.RequestMethod.*; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.Errors; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import spittr.Spitter; import spittr.data.SpitterRepository; @Controller @RequestMapping("/spitter") public class SpitterController { @RequestMapping(value="/register", method=POST) public String processRegistration( @Valid Spitter spitter, Errors errors) { if (errors.hasErrors()) { return "registerForm"; } spitterRepository.save(spitter); return "redirect:/spitter/" + spitter.getUsername(); }
讲传输的表单数据转换成pojo,并且进行了验证。如果有错误的话讲错误放到Errors errors,然后在控制层判断errors,如果有错误回到提交表单页面,如果正确跳转到正确的页面。
如果公司喜欢在控制层编写if去判断,那就去编写if语句吧。