Spring MVC框架在進行表單提交,自動封裝成物件提交,在以物件的形式入參
阿新 • • 發佈:2018-12-13
最近做了一個超市訂單管理系統的專案,使用的是Spring MVC 和Spring 框架。
如上圖:進行新使用者新增。此處jsp頁面程式碼如下:
<div class="right"> <div class="location"> <strong>你現在所在的位置是:</strong> <span>使用者管理頁面 >> 使用者新增頁面</span> </div> <div class="providerAdd"> <form id="userForm" name="userForm" method="post" enctype="multipart/form-data" action="${pageContext.request.contextPath }/user/addsave.html"> <input type="hidden" name="method" value="add"> <!--div的class 為error是驗證錯誤,ok是驗證成功--> <div> <label for="userCode">使用者編碼:</label> <input type="text" name="userCode" id="userCode" value=""> <!-- 放置提示資訊 --> <font color="red"></font> </div> <div> <label for="userName">使用者名稱稱:</label> <input type="text" name="userName" id="userName" value=""> <font color="red"></font> </div> <div> <label for="userPassword">使用者密碼:</label> <input type="password" name="userPassword" id="userPassword" value=""> <font color="red"></font> </div> <div> <label for="ruserPassword">確認密碼:</label> <input type="password" name="ruserPassword" id="ruserPassword" value=""> <font color="red"></font> </div> <div> <label >使用者性別:</label> <select name="gender" id="gender"> <option value="1" selected="selected">男</option> <option value="2">女</option> </select> </div> <div> <label for="birthday">出生日期:</label> <input type="text" Class="Wdate" id="birthday" name="birthday" readonly="readonly" onclick="WdatePicker();"> <font color="red"></font> </div> <div> <label for="phone">使用者電話:</label> <input type="text" name="phone" id="phone" value=""> <font color="red"></font> </div> <div> <label for="address">使用者地址:</label> <input name="address" id="address" value=""> </div> <div> <label >使用者角色:</label> <!-- 列出所有的角色分類 --> <!-- <select name="userRole" id="userRole"></select> --> <select name="userRole" id="userRole"> <option value="1">系統管理員</option> <option value="2">經理</option> <option value="3" selected="selected">普通使用者</option> </select> <font color="red"></font> </div> <div> <input type="hidden" id="errorinfo" value="${uploadFileError}"> <label for="a_idPicPath">證件照:</label> <input type="file" name="attachs" id="a_idPicPath" value=""> <font color="red"></font> </div> <div> <input type="hidden" id="errorinfo_wp" value="${uploadwpError}"> <label for="a_workPicPath">工作證照片:</label> <input type="file" name="attachs" id="a_workPicPath" value=""> <font color="red"></font> </div> <div class="providerAddBtn"> <input type="button" name="add" id="add" value="儲存" > <input type="button" id="back" name="back" value="返回" > </div> </form> </div> </div>
下面的是實體類程式碼:
package cn.smbms.pojo; import java.util.Date; import javax.validation.constraints.NotNull; import javax.validation.constraints.Past; import org.hibernate.validator.constraints.Length; import org.hibernate.validator.constraints.NotEmpty; import org.springframework.format.annotation.DateTimeFormat; public class User { private Integer id; //id @NotEmpty(message="使用者編碼不能為空") //伺服器進行驗證 private String userCode; //使用者編碼 @NotEmpty(message="使用者名稱稱不能為空") private String userName; //使用者名稱稱 @NotNull(message="使用者密碼不能為空") @Length(min=6,max=16,message="使用者密碼長度為6-10位") private String userPassword; //使用者密碼 private Integer gender; //性別 @Past(message="必須是一個過去時間") @DateTimeFormat(pattern="yyyy-MM-dd") private Date birthday; //出生日期 private String phone; //電話 private String address; //地址 private Integer userRole; //使用者角色 private Integer createdBy; //建立者 private Date creationDate; //建立時間 private Integer modifyBy; //更新者 private Date modifyDate; //更新時間 private Integer age;//年齡 private String userRoleName; //使用者角色名稱 private String idPicPath; //檔案上傳路徑 private String workPicPath; //工作證上傳路徑 public String getWorkPicPath() { return workPicPath; } public void setWorkPicPath(String workPicPath) { this.workPicPath = workPicPath; } public void setAge(Integer age) { this.age = age; } public String getIdPicPath() { return idPicPath; } public void setIdPicPath(String idPicPath) { this.idPicPath = idPicPath; } public User(){} public User(Integer id,String userCode,String userName,String userPassword,Integer gender,Date birthday,String phone, String address,Integer userRole,Integer createdBy,Date creationDate,Integer modifyBy,Date modifyDate){ this.id = id; this.userCode = userCode; this.userName = userName; this.userPassword = userPassword; this.gender = gender; this.birthday = birthday; this.phone = phone; this.address = address; this.userRole = userRole; this.createdBy = createdBy; this.creationDate = creationDate; this.modifyBy = modifyBy; this.modifyDate = modifyDate; } public String getUserRoleName() { return userRoleName; } public void setUserRoleName(String userRoleName) { this.userRoleName = userRoleName; } public Integer getAge() { /*long time = System.currentTimeMillis()-birthday.getTime(); Integer age = Long.valueOf(time/365/24/60/60/1000).IntegerValue();*/ Date date = new Date(); Integer age = date.getYear()-birthday.getYear(); return age; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUserCode() { return userCode; } public void setUserCode(String userCode) { this.userCode = userCode; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getUserPassword() { return userPassword; } public void setUserPassword(String userPassword) { this.userPassword = userPassword; } public Integer getGender() { return gender; } public void setGender(Integer gender) { this.gender = gender; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public Integer getUserRole() { return userRole; } public void setUserRole(Integer userRole) { this.userRole = userRole; } public Integer getCreatedBy() { return createdBy; } public void setCreatedBy(Integer createdBy) { this.createdBy = createdBy; } public Date getCreationDate() { return creationDate; } public void setCreationDate(Date creationDate) { this.creationDate = creationDate; } public Integer getModifyBy() { return modifyBy; } public void setModifyBy(Integer modifyBy) { this.modifyBy = modifyBy; } public Date getModifyDate() { return modifyDate; } public void setModifyDate(Date modifyDate) { this.modifyDate = modifyDate; } }
下面的是控制層的使用者增加方法:
@RequestMapping(value="/addsave.html",method=RequestMethod.POST) public String addSave( User user,HttpSession session, HttpServletRequest request, @RequestParam(value="attachs",required=false)MultipartFile[] attachs){ String idPicPath=null; String workPicPath=null; String errorInfo=null; boolean flag=true; //定義上傳目標路徑 String path = request.getSession().getServletContext(). getRealPath("statics"+File.separator+"uploadfiles"); for(int i=0;i<attachs.length;i++){ MultipartFile attach=attachs[i]; //判斷上傳檔案是否為空 if(!attach.isEmpty()){ if(i==0){ errorInfo="uploadFileError"; }else if(i==1){ errorInfo="uploadwpError"; } logger.info("uploadFile path ============== > "+path); //獲取原檔名 String oldFileName=attach.getOriginalFilename(); logger.info("uploadFile oldFileName ============== > "+oldFileName); //獲取檔案字尾 String prefix=FilenameUtils.getExtension(oldFileName); logger.debug("uploadFile prefix============> " + prefix); int filesize=500000; logger.debug("uploadFile size============> " + attach.getSize()); //判斷檔案大小 if(attach.getSize()>filesize){ request.setAttribute(errorInfo, "上傳檔案大小不能超過500k"); flag=false; }else if(prefix.equalsIgnoreCase("jpg") ||prefix.equalsIgnoreCase("jpeg") ||prefix.equalsIgnoreCase("png") ||prefix.equalsIgnoreCase("pneg") ){ //判斷格式是否正確 和給圖片重新命名: 當前系統時間+隨機數+"_Personal.jpg" String fileName=System.currentTimeMillis()+RandomUtils.nextInt(1000000)+"_Personal.jpg"; logger.debug("new fileName======== " + fileName); //創界檔案用來接收上傳的檔案流 File targetFile=new File(path,fileName); if(!targetFile.exists()){ targetFile.mkdirs(); } try { attach.transferTo(targetFile); } catch (Exception e) { e.printStackTrace(); request.setAttribute(errorInfo, "*上傳失敗"); flag=false; } //File.separator自適應分隔符/,linux系統或則其他系統/可能不相容 if(i==0){ idPicPath=path+File.separator+fileName; }else if(i==1){ workPicPath=path+File.separator+fileName; } }else{ request.setAttribute(errorInfo, "上傳圖片格式不正確"); flag=false; } } }
在增加方法中,直接以實體物件的方式入參,Spring MVC框架自動將屬性封裝成物件,在沒用框架的時候,一般是在servlet中通過request.getParameter("")的方法來獲取屬性,在通過實體類的set方法給實體類賦值,而Spring MVC框架恰好將此步驟省略,注意:input標籤中的name屬性名稱要與實體類中的屬性名稱一致.
此處程式碼也介紹了多檔案上傳的過程,使用陣列方式實現多檔案上傳,在控制層中,在for迴圈中進行判斷,需要注意的是要注意後臺的順序要和上傳的順序一致。此處是兩檔案上傳也可以用兩個單檔案上傳完成,也比較清晰明瞭。