1、spring3.0 MVC初步2,从spring2.0转向spring3.0,显示和提交form,显示,带上空数据 RequestMapping(method = RequestMethod.GET, params = “register“) public String prepare(Model model) Member m = new Member();model.addAttribute(m);return “member/edit“;,form用spring标签库的几个标签,用户名: 密码: Email Address:modelAttribute:数据 path:属性,处理form
2、提交,RequestMapping(method = RequestMethod.POST) public String register(Member member,BindingResult bindingResult,) if (bindingResult.hasErrors() return “member/edit“;service.addMember(member);return “redirect:/member/“+member.getMemberName(); URLEncoder.encode用来处理重定向时的中文问题,验证用到的jar,validation-api-1.0
3、.0.GA.jar hibernate-validator-4.0.2.GA.jar,验证提交, 用户名:密码:Email Address:,验证-控制器,public String register(Valid Member member,BindingResult bindingResult,) .,验证-bean,public class Member Size(min=3, max=20, message=“Username must be between 3 and 20 characters long.“) Pattern(regexp=“a-zA-Z0-9+$“, message
4、=“Username must be alphanumeric with no spaces“) private String memberName; Size(min=6, max=20,message=“The password must be at least 6 characters long.“) private String password; .,中文乱码问题解决web.xml,characterEncodingFilterorg.springframework.web.filter.CharacterEncodingFilterencodingUTF-8forceEncodin
5、gtrue,中文乱码问题解决web.xml,characterEncodingFilter/*,文件上传用到的jar,commons-io-2.0.1.jar commons-fileupload-1.2.2.jar,文件上传form,上传处理Controller,RequestMapping(method = RequestMethod.POST) public String register( RequestParam(value = “image“, required = false) MultipartFile image) try if (!image.isEmpty() valid
6、ateImage(image);saveImage(member.getMemberName() + “.jpg“, image); / catch (Exception e) bindingResult.reject(e.getMessage(); return “member/edit“; return “redirect:/member/“+member.getMemberName();,上传处理validateImage,private void validateImage(MultipartFile image)throws Exception if (!image.getConte
7、ntType().equals(“image/pjpeg“) throw new Exception(“Only JPG images accepted“); ,上传处理saveImage,private void saveImage(String filename, MultipartFile image) throws Exception try File file = new File(webRootPath + “/resources/“ + filename);FileUtils.writeByteArrayToFile(file, image.getBytes(); catch (IOException e) throw new Exception(“Unable to save image“, e); FileUtils在commons-fileupload-1.2.2.jar中,