spring3.0 MVC筆記2–從spring2.0轉向spring3.0 – JAVA編程語言程序開發技術文章

7、顯示和提交form

顯示,帶上空數據
 @RequestMapping(method = RequestMethod.GET, params = "register")
 public String prepare(Model model) {
  Member m = new Member();
  model.addAttribute(m);
  return "member/edit";
 }

form用spring標簽庫的幾個標簽

<%@ taglib prefix="sf" uri="https://www.springframework.org/tags/form"%>
<sf:form method="POST" modelAttribute="member">
用戶名:<sf:input path="memberName"/>
密碼:<sf:password path="password"/>
Email Address:<sf:input path="email"/>
<input type="submit"/>
</sf:form>

modelAttribute:數據
path:屬性

8、處理form提交

 @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用來處理重定向時的中文問題

 

9、驗證提交

<sf:form method="POST" modelAttribute="member">
用戶名:<sf:input path="memberName"/>
<sf:errors path="memberName" cssClass="error" />
密碼:<sf:password path="password"/>
<sf:errors path="password" cssClass="error" />
Email Address:<sf:input path="email"/>
<sf:errors path="email" cssClass="error" />
<input type="submit"/>
</sf:form>

控制器:
 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="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;
…}

10、中文亂碼問題解決

web.xml

 <filter>
    <filter-name>characterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>characterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

11、文件上傳

 <bean id="multipartResolver" class=
  "org.springframework.web.multipart.commons.CommonsMultipartResolver">
  <property name="maxUploadSize" value="500000"/>
 </bean>

<sf:form method="POST" modelAttribute="member" enctype="multipart/form-data">
<input name="image" type="file"/>
<input type="submit"/>

上傳處理
 @RequestMapping(method = RequestMethod.POST)
 public String register(   @RequestParam(value = "image", required = false) MultipartFile image) {
  try {
   if (!image.isEmpty()) {
    validateImage(image);
    saveImage(member.getMemberName() + ".jpg", image); //
   }
  } catch (Exception e) {
   bindingResult.reject(e.getMessage());
   return "member/edit";
  }
  return "redirect:/member/"+member.getMemberName();
  }
 }

 private void validateImage(MultipartFile image) throws Exception {
  if (!image.getContentType().equals("image/pjpeg")) {
   throw new Exception("Only JPG images accepted");
  }
 }

 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);
  }
 }

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。