在学习spring mvc注解校验的时候发现@NotNull没有起作用!如uname.而password的@Size能行.哪位达达指导下,告诉我问题出在哪里!
代码如下
- Java code
package com.zed.model;import javax.validation.constraints.NotNull;import javax.validation.constraints.Size;public class User { @NotNull(message="用户名不能为空") private String uname; @Size(min=4,max=8, message="密码长度应为{min}-{max}位") private String password; public String getUname() { return uname; } public void setUname(String uname) { this.uname = uname; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
控制器代码
- Java code
package com.zed.web;import javax.validation.Valid;import org.springframework.stereotype.Controller;import org.springframework.validation.BindingResult;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import com.zed.model.User;@Controllerpublic class UserController { @RequestMapping(value="/userLogin", method=RequestMethod.POST) public String userLogin(@Valid User user, BindingResult result) { if(result.hasErrors()) { return "home"; } else { return "success"; } }}
spring文件配置关键部分
- XML code
<context:component-scan base-package="com.zed" /><mvc:annotation-driven /><bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/" /> <property name="suffix" value=".jsp" /></bean>
简单的表单
- HTML code
<form action="userLogin" method="post"> <label>user name</label> <input name="uname" type="text"> <label>password</label> <input name="password" type="text"> <input type="submit" value="submit"> </form>
------解决方案--------------------------------------------------------
你先测试一下变量
------解决方案--------------------------------------------------------
知道null和""有区别不?