一、如何传递参数
@RequestMapping("/detail")
public String detail(@RequestParam("id") int id,Model model){
Category category=new Category();
category.setCateId(id);
category.setCateName("测试分类"+id);
model.addAttribute("cate",category);
return "detail.html";
}
@RequestMapping(value = "/edit/{id}",method = RequestMethod.GET)
public String edit(@PathVariable("id") int id,Model model) {
//todo:get category from db
Category category=new Category();
category.setCateId(id);
category.setCateName("测试分类"+id);
model.addAttribute("cate",category);
return "edit.html";
}
二、校验表单
1.首先定义实体类。
public class Category{
public Category(){}
@NotNull
@Min(1)
private int cateId;
@NotNull
private String cateName;
public int getCateId() {
return cateId;
}
public void setCateId(int cateId) {
this.cateId = cateId;
}
public String getCateName() {
return cateName;
}
public void setCateName(String cateName) {
this.cateName = cateName;
}
}
2.表单edit.html
id: | |
name: | |
3.通过给action方法的参数添加@Valid注解,这会告知Spring,需要确保这个对象满足校验限制
@RequestMapping(value = "/save",method = RequestMethod.POST)
public String save( @Valid Category category, Errors errors) throws IOException {...}
错误可以通过Errors对象进行访问,现在这个对象已作为processRegistration()方法的参数。(很重要一点需要注意,Errors参数要紧跟在带有@Valid注解的参数后面,@Valid注解所标注的就是要检验的参数。
三、上传图片
1.设置web.xml配置
web.xml配置multipart-config
springmvc
org.springframework.web.servlet.DispatcherServlet
1
2097152
4194304
2.from表单
form要将enctype属性设置为multipart/form-data,这就告诉浏览器以multipart数据的形式提交表单
input标签要把type设置为file,这能够让用户选择要上传的图片文件。accept属性用来将文件类型限制为JPEG、PNG以及GIF图片。根据其name属性,图片数据将会发送到multipart请求中的profilePicture part之中
id: | |
name: | |
file: | |
3.controller:
@RequestPart :图片对应的参数要添加该注解
spring提供了Multipart MultipartFile对象,它为处理multipart数据提供了内容更为丰富的对象
transferTo() ,它能够帮助我们将上传的文件写入到文件系统中
@RequestMapping(value = "/save",method = RequestMethod.POST)
public String save(@RequestPart("picture") MultipartFile picture, @Valid Category category, Errors errors) throws IOException {
//todo:save file to image server
String filepath=request.getRealPath("/")+"upload/"+picture.getOriginalFilename();
picture.transferTo(new File(filepath));
if(errors.hasErrors()){
return "edit.html";
}
//todo:save category to db
return "redirect:/category/detail?id="+category.getCateId();
}