@Controller @RequestMapping("/form") public class formController { @RequestMapping(value="/add",method=RequestMethod.POST) public String add(@Valid User u,BindingResult br){ if(br.getErrorCount()>0){ return "addUser"; } return "showUser"; } @RequestMapping(value="/add",method=RequestMethod.GET) public String add(Map<String,Object> map){ map.put("user",new User()); return "addUser"; } }
ps:
1.因为jsp中使用了modelAttribute属性,所以必须在request域中有一个"user".
2.@Valid 表示按照在实体上标记的注解验证参数
3.返回到原页面错误信息回回显,表单也会回显
5.错误信息自定义
在src目录下添加locale.properties
NotEmpty.user.name=name can't not be empty Past.user.birth=birth should be a past value DateTimeFormat.user.birth=the format of input is wrong typeMismatch.user.birth=the format of input is wrong typeMismatch.user.id=the format of input is wrong
在SpringMVC配置文件中配置
6.国际化显示
在src下添加locale_zh_CN.properties
username=账号 password=密码
locale.properties中添加
username=user name password=password
创建一个locale.jsp
在SpringMVC中配置
让locale.jsp在WEB-INF下也能直接访问
最后,访问locale.jsp,切换浏览器语言,能看到账号和密码的语言也切换了
十七、压轴大戏--整合SpringIOC和SpringMVC1.创建一个test.SpringMVC.integrate的包用来演示整合,并创建各类
2.User实体类
public class User { public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getBirth() { return birth; } public void setBirth(Date birth) { this.birth = birth; } @Override public String toString() { return "User [id=" + id + ",, birth=" + birth + "]"; } private int id; @NotEmpty private String name; @Past @DateTimeFormat(pattern="yyyy-MM-dd") private Date birth; }
3.UserService类
@Component
public class UserService {
public UserService(){
System.out.println("UserService Constructor...\n\n\n\n\n\n");
}
public void save(){
System.out.println("save");
}
}
4.UserController
@Controller @RequestMapping("/integrate") public class UserController { @Autowired private UserService userService; @RequestMapping("/user") public String saveUser(@RequestBody @ModelAttribute User u){ System.out.println(u); userService.save(); return "hello"; } }
5.Spring配置文件
在src目录下创建SpringIOC的配置文件applicationContext.xml
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans " xmlns:util="http://www.springframework.org/schema/util" xmlns:p="http://www.springframework.org/schema/p" xmlns:context expression expression
在Web.xml中添加配置
org.springframework.web.context.ContextLoaderListenercontextConfigLocationclasspath:applicationContext.xml
6.在SpringMVC中进行一些配置,防止SpringMVC和SpringIOC对同一个对象的管理重合
expression expression
十八、SpringMVC详细运行流程图 十九、SpringMVC运行原理