在web開發中通常會有文件上傳的操做java
通常JavaWeb開發中文件上傳使用的 Apache組織的Commons FileUpload組件web
SpringMVC中使用 MultipartFile file對象接受上傳文件,必須保證 後臺參數的名稱和表單提交的文件的名稱一致spring
文件上傳必須條件數據庫
表單的 enctype="multipart/form-data"apache
1 <fieldset> 2 <legend>單個文件上傳</legend> 3 <form action="${pageContext.request.contextPath}/upload.do" method="post" enctype="multipart/form-data"> 4 姓名: <input name="username"><br> 5 頭像: <input type="file" name="headImg"><br> 6 <button type="submit">提交</button> 7 </form> 8 </fieldset>
SpringMVC中使用 MultipartFile file對象接受上傳文件,必須保證 後臺方法MultipartFile 參數的名稱和表單提交的文件的名稱一致數組
1 //SpringMVC中使用 MultipartFile file對象接受上傳文件,必須保證 後臺參數的名稱和表單提交的文件的名稱一致 2 @RequestMapping("/upload") 3 public String singleUpload(MultipartFile headImg,@RequestParam("username")String username) throws IOException { 4 5 System.out.println(headImg.getName());//獲取上傳文件的表單名稱 6 System.out.println(headImg.getContentType());//MIME類型 7 System.out.println(headImg.getSize());//文件大小 8 System.out.println(headImg.getOriginalFilename());//獲取上傳文件的完整名稱 9 //獲取上傳文件對應的輸入流 10 //InputStream in = headImg.getInputStream(); 11 12 //建立一個磁盤目錄用於保存文件 13 File destFile= new File("c:/upload"); 14 if(!destFile.exists()) { 15 destFile.mkdir(); 16 } 17 //使用uuid做爲文件隨機名稱 18 String fileName = UUID.randomUUID().toString().replaceAll("-", ""); 19 //使用FileNameUtils獲取上傳文件名的後綴 20 String extension = FilenameUtils.getExtension(headImg.getOriginalFilename());// jpg , png 等等 21 //建立新的文件名稱 22 String newFileName = fileName + "."+extension; 23 24 //建立要保存文件的File對象 25 File file = new File(destFile, newFileName); 26 //保存文件到本地磁盤 27 headImg.transferTo(file); 28 29 return "redirect:/upload.jsp"; 30 }
1 配置文件上傳解析器:bean的名字是固定的 2 使用spring表達式 #{1024*1024} 3 4 <!-- 配置文件上傳解析器:bean的名字是固定的,底層使用的名稱注入 --> 5 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 6 <!-- 設置上傳文件的最大尺寸爲1MB --> 7 <property name="maxUploadSize" value="#{1024 * 1024}"></property> 8 </bean>
1 <fieldset> 2 <legend>單個文件上傳</legend> 3 <form action="${pageContext.request.contextPath}/uploads.do" method="post" enctype="multipart/form-data"> 4 文件1: <input type="file" name="headImgs"><br> 5 文件2: <input type="file" name="headImgs"><br> 6 文件3: <input type="file" name="headImgs"><br> 7 <button type="submit">提交</button> 8 </form> 9 </fieldset>
1 @RequestMapping("/uploads") 2 public String singleUploads(MultipartFile[] headImgs) throws IOException { 3 4 5 //建立一個磁盤目錄用於保存文件 6 File destFile= new File("c:/upload"); 7 if(!destFile.exists()) { 8 destFile.mkdir(); 9 } 10 for (int i = 0; i < headImgs.length; i++) { 11 MultipartFile headImg = headImgs[i]; 12 13 //使用uuid做爲文件隨機名稱 14 String fileName = UUID.randomUUID().toString().replaceAll("-", ""); 15 //使用FileNameUtils獲取上傳文件名的後綴 16 String extension = FilenameUtils.getExtension(headImg.getOriginalFilename());// jpg , png 等等 17 //建立新的文件名稱 18 String newFileName = fileName + "."+extension; 19 20 //建立要保存文件的File對象 21 File file = new File(destFile, newFileName); 22 //保存文件到本地磁盤 23 try { 24 headImg.transferTo(file); 25 } catch (Exception e) { 26 e.printStackTrace(); 27 } 28 } 29 return "redirect:/upload.jsp"; 30 }
文件下載,SpringMVC並無作過多的封裝,仍是使用原來的下載方式瀏覽器
1 package cn.zj.springmvc.controller; 2 3 import java.io.FileInputStream; 4 import java.io.IOException; 5 6 import javax.servlet.ServletOutputStream; 7 import javax.servlet.http.HttpServletResponse; 8 9 import org.apache.commons.io.IOUtils; 10 import org.springframework.stereotype.Controller; 11 import org.springframework.web.bind.annotation.RequestMapping; 12 13 @Controller 14 public class DownloadController { 15 /* 16 * 下載文件思路 17 * 1. 接受須要下載文件名稱,根據文件名稱,找到磁盤對應的文件,讀取到內存中造成一個輸入流 18 * 2. 將輸入流經過響應對象(HttpServletResponse)響應給瀏覽器(下載) 19 * 20 * 注意:Web通常只會下載小型文件 21 * 22 */ 23 @RequestMapping("/download") 24 public void upload(String fileName ,HttpServletResponse response) throws IOException { 25 //0. 判斷是否vip,有積分,金豆 26 //TODO 27 28 //1. 接受文件名,讀取磁盤對應的文件,建立輸入流對象 29 30 FileInputStream inputStream = new FileInputStream("C:/"+fileName); 31 32 //2.獲取響應對象的輸出流 33 ServletOutputStream outputStream = response.getOutputStream(); 34 35 36 //3.文件下載文件名的編碼使用ISO-08859-1編碼 37 //咱們須要將咱們UTF-8的 filename轉換ISO-8859-1編碼 38 //3.1先將字符串以UTF-8轉換成字節數組 39 byte[] bytes = fileName.getBytes("UTF-8"); 40 //3.2再將字節數組以 ISO-8859-1轉換字符串 41 fileName = new String(bytes, "ISO-8859-1"); 42 43 44 //4.響應的內容應該是以附件的形式響應給瀏覽器(設置響應頭) 45 response.setHeader("Content-Disposition", "attachment;filename="+fileName); 46 47 //5.響應文件給瀏覽器 48 IOUtils.copy(inputStream, outputStream); 49 50 } 51 52 }
攔截器 : Interceptorspring-mvc
Spring MVC 的攔截器相似於Servlet 開發中的過濾器Filter,用於對Controller進行預處理和後處理。mvc
使用SpringMVC攔截器步驟:app
1)定義攔截器類,實現接口 org.springframework.web.servlet.HandlerInterceptor
2)在applicationContext.xml中配置攔截器
攔截器方法的執行時機:
1):preHandle:控制器方法執行以前執行,返回結果爲true表示放行,若是返回爲false,表示攔截(能夠作權限攔截,登陸檢查攔截).
2):postHandle:控制器方法執行後,視圖渲染以前執行(能夠加入統一的響應信息).
3):afterCompletion:視圖渲染以後執行(處理Controller異常信息,記錄操做日誌,清理資源等)
1 public class CheckLoginInterceptor implements HandlerInterceptor { 2 //1):preHandle:控制器方法執行以前執行,返回結果爲true表示放行,若是返回爲false,表示攔截(能夠作權限攔截,登陸檢查攔截). 3 // true : 放行 false :不放行 4 @Override 5 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) 6 throws Exception { 7 8 System.out.println("攔截器執行了......"); 9 //從Session中獲取登陸信息 10 String username = (String)request.getSession().getAttribute("username"); 11 System.out.println(username); 12 13 if(username !=null) { 14 //放行 15 return true; 16 }else { 17 //跳轉到登陸頁面去 18 response.sendRedirect(request.getContextPath()+"/login.jsp"); 19 return false; 20 } 21 } 22 23 //postHandle:控制器方法執行後,視圖渲染以前執行(能夠加入統一的響應信息). 24 @Override 25 public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, 26 ModelAndView modelAndView) throws Exception { 27 } 28 29 //afterCompletion:視圖渲染以後執行(處理Controller異常信息,記錄操做日誌,清理資源等 30 @Override 31 public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) 32 throws Exception { 33 } 34 }
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:p="http://www.springframework.org/schema/p" 4 xmlns:mvc="http://www.springframework.org/schema/mvc" 5 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 6 xsi:schemaLocation=" 7 http://www.springframework.org/schema/beans 8 http://www.springframework.org/schema/beans/spring-beans.xsd 9 http://www.springframework.org/schema/mvc 10 http://www.springframework.org/schema/mvc/spring-mvc.xsd 11 "> 12 13 <!-- 配置springmvc的註解驅動 --> 14 <mvc:annotation-driven/> 15 16 17 18 <!-- 配置攔截器 :能夠有多個攔截器--> 19 <mvc:interceptors> 20 <!--配置檢查登陸攔截器 --> 21 <mvc:interceptor> 22 23 <!-- 配置攔截的規則 24 只會攔截 控制器請求,不會攔截jsp頁面 25 /* 26 只能攔截一級 如 : /list.do /delete.do 27 如:/user/list.do , /user/delete.do 二級 不能攔截 28 /** 29 能夠攔截多級 不管幾級均可以 如 /a/b/c/d/list.do 30 --> 31 <mvc:mapping path="/**"/> 32 33 <!-- 排除攔截的地址,多個地址使用逗號隔開 34 /user/login.do 35 36 37 --> 38 <mvc:exclude-mapping path="/user/login.do"/> 39 40 <!-- 攔截器的類型 --> 41 <bean class="cn.zj.ssm.interceptor.CheckLoginInterceptor"/> 42 43 </mvc:interceptor> 44 </mvc:interceptors> 45 46 47 </beans>
使用POI組件實現Excel數據的處理.
1 //使用POI建立excel文件到本地 2 @Test 3 public void testName() throws Exception { 4 //1.建立數據,用於本地建立excel 5 HSSFWorkbook book = new HSSFWorkbook(); 6 //2.建立一個sheet 工做區域 7 HSSFSheet sheet = book.createSheet(); 8 //3.建立一行: 從0開始,表明第一行 9 HSSFRow row = sheet.createRow(0); 10 //4.建立一個個單元格 11 HSSFCell cell1 = row.createCell(0); 12 //5.設置單元格的數據 13 cell1.setCellValue("張三"); 14 15 HSSFCell cell2 = row.createCell(1); 16 cell2.setCellValue(20); 17 18 //將數據保存到本地 19 try { 20 book.write(new File("d:/測試.xlsx")); 21 } catch (Exception e) { 22 e.printStackTrace(); 23 // TODO: handle exception 24 } 25 }
1 // 導出用戶信息 2 @RequestMapping("/exprot") 3 public void export(HttpServletResponse response) { 4 5 6 //建立POI的數據對象 7 HSSFWorkbook book = new HSSFWorkbook(); 8 //建立sheet 9 HSSFSheet sheet = book.createSheet(); 10 //建立標題列 11 HSSFRow titleRow = sheet.createRow(0); 12 //建立表單單元格並設置值 13 titleRow.createCell(0).setCellValue("編號"); 14 titleRow.createCell(1).setCellValue("姓名"); 15 titleRow.createCell(2).setCellValue("郵箱"); 16 titleRow.createCell(3).setCellValue("電話"); 17 18 List<User> users = service.list(); 19 //循環學生 20 for (int i = 0; i < users.size(); i++) { 21 //獲取每一個學生 22 User user = users.get(i); 23 //建立學生列 24 HSSFRow row = sheet.createRow(i+1); 25 //建立學生信息對應的單元格並設置數據 26 row.createCell(0).setCellValue(user.getId()); 27 row.createCell(1).setCellValue(user.getName()); 28 row.createCell(2).setCellValue(user.getEmail()); 29 row.createCell(3).setCellValue(user.getPhone()); 30 } 31 32 try { 33 //設置響應頭,響應的內容是爲附件形式 34 response.addHeader("Content-Disposition", 35 "attachment;filename=" + new String("學生信息.xlsx".getBytes(), "ISO-8859-1")); 36 37 book.write(response.getOutputStream()); 38 } catch (Exception e) { 39 e.printStackTrace(); 40 } 41 }
Spring 容器建立的對象默認 都是單例 對象
SpringMVC對象 Controller的對象的建立有三種狀況
Request : 在用戶的一次請求中生效(用戶每次請求都會建立Controller對象)多例
Session : Controller對象在一次會話中建立一個對象
若是控制器中有成員變量 設置或者賦值操做,必須使用 request 返回