SpringMVC-08-攔截器、檔案上傳與下載
攔截器
SpringMVC的處理器攔截器類似於Servlet開發中的過濾器Filter,用於對處理器進行預處理和後處理。開發者可以自己定義一些攔截器來實現特定的功能。
過濾器與攔截器的區別:攔截器是AOP思想的具體應用。
過濾器
Servlet規範中的一部分,任何java web工程都可以使用。
在url-pattern中配置了/*之後,可以對所有要訪問的資源進行攔截。
攔截器
攔截器是SpringMVC框架自己的,只有使用了SpringMVC框架的工程才能使用。
攔截器只會攔截訪問控制器方法,如果訪問的是jsp/html/css/image/js是不會進行攔截的。
自定義攔截器
想要自定義攔截器,必須實現HanderInterceptor介面
package com.li.interceptor; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class MyInterceptor implements HandlerInterceptor {//在請求處理的方法之前執行 //如果返回true執行下一個攔截器 //如果返回false就不執行下一個攔截器 public boolean preHandle(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse, Object o) throws Exception { System.out.println("------------處理前------------"); return true; } //在請求處理方法執行之後執行 publicvoid postHandle(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView)throws Exception { System.out.println("------------處理後------------"); } //在dispatcherServlet處理後執行,做清理工作. public void afterCompletion(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { System.out.println("------------清理------------"); } }
在springmvc的配置檔案中配置攔截器
<!--關於攔截器的配置--> <mvc:interceptors> <mvc:interceptor> <!--/** 包括路徑及其子路徑--> <!--/admin/* 攔截的是/admin/add等等這種 , /admin/add/user不會被攔截--> <!--/admin/** 攔截的是/admin/下的所有--> <mvc:mapping path="/**"/> <!--bean配置的就是攔截器--> <bean class="com.li.interceptor.MyInterceptor"/> </mvc:interceptor> </mvc:interceptors>
package com.li.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; //測試攔截器的控制器 @Controller public class InterceptorController { @RequestMapping("/interceptor") @ResponseBody public String testFunction() { System.out.println("控制器中的方法執行了"); return "hello"; } }
<a href="${pageContext.request.contextPath}/interceptor">攔截器測試</a>
示例:驗證使用者是否登入
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <h1>登入頁面</h1> <hr> <body> <form action="${pageContext.request.contextPath}/user/login"> 使用者名稱:<input type="text" name="username"> <br> 密碼:<input type="password" name="pwd"> <br> <input type="submit" value="提交"> </form> </body> </html>
package com.li.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpSession; @Controller @RequestMapping("/user") public class UserController { //跳轉到登陸頁面 @RequestMapping("/jumplogin") public String jumpLogin() throws Exception { return "login"; } //跳轉到成功頁面 @RequestMapping("/jumpSuccess") public String jumpSuccess() throws Exception { return "success"; } //登陸提交 @RequestMapping("/login") public String login(HttpSession session, String username, String pwd) throwsException { // 向session記錄使用者身份資訊 System.out.println("接收前端==="+username); session.setAttribute("user", username); return "success"; } //退出登陸 @RequestMapping("logout") public String logout(HttpSession session) throws Exception { // session 過期 session.invalidate(); return "login"; } }
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>登入成功頁面</h1>
<hr>
${user}
<a href="${pageContext.request.contextPath}/user/logout">登出</a>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>$Title$</title> </head> <body> <h1>首頁</h1> <hr> <%--登入--%> <a href="${pageContext.request.contextPath}/user/jumplogin">登入</a> <a href="${pageContext.request.contextPath}/user/jumpSuccess">成功頁面</a> </body> </html>
package com.li.interceptor; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; public class LoginInterceptor implements HandlerInterceptor { public boolean preHandle(HttpServletRequest request, HttpServletResponseresponse, Object handler) throws ServletException, IOException { // 如果是登陸頁面則放行 System.out.println("uri: " + request.getRequestURI()); if (request.getRequestURI().contains("login")) { return true; } HttpSession session = request.getSession(); // 如果使用者已登陸也放行 if(session.getAttribute("user") != null) { return true; } // 使用者沒有登陸跳轉到登陸頁面 request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request,response); return false; } public void postHandle(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView)throws Exception { } public void afterCompletion(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { } }
<!--關於攔截器的配置--> <mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/**"/> <bean id="loginInterceptor" class="com.li.interceptor.LoginInterceptor"/> </mvc:interceptor> </mvc:interceptors>
檔案上傳和下載
檔案上傳和下載是專案開發中最常見的功能之一,springmvc可以很好的支援檔案上傳與下載。但是SpringMVC上下文中預設沒有裝配MultipartResolver,因此預設情況下其不能處理檔案上傳工作。如果想要使用Spring的檔案上傳功能,則需要在上下文中配置MultipartResolver。
前端表單要求:為了能上傳檔案,必須將表單的method設定為POST,並將enctype設定為multipart/form-data。只有在這樣的情況下,瀏覽器才會把使用者選擇的檔案以二進位制資料傳送給伺服器。
<form action="" enctype="multipart/form-data" method="post"> <input type="file" name="file"/> <input type="submit"> </form>
一旦設定了enctype為multipart/form-data。瀏覽器即會採用二進位制流的方式來處理表單資料,而對於檔案上傳的處理則涉及在服務端解析原始的HTTP響應。
SpringMVC為檔案上傳提供了直接的支援,這種支援是用即插即用的MultipartResolver實現的。SpringMVC使用Apache Commons FileUpload技術實現了一個MultipartResolver實現類:CommonsMultipartResolver,因此,SpringMVC的檔案上傳還需要依賴Apache Commons FileUpload的元件。
檔案上傳
1.匯入檔案上傳的jar包,commons-fileupload,maven會自動匯入其依賴的包commons-io包。
<!--檔案上傳--> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.3</version> </dependency> <!--servlet-api匯入高版本的--> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> </dependency>
2.配置bean:multipartResolver
注意id必須為multipartResolver,否則上傳檔案會報400的錯誤。
<!--檔案上傳配置--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 請求的編碼格式,必須和jSP的pageEncoding屬性一致,以便正確讀取表單的內容,預設為ISO-8859-1 --> <property name="defaultEncoding" value="utf-8"/> <!-- 上傳檔案大小上限,單位為位元組(10485760=10M) --> <property name="maxUploadSize" value="10485760"/> <property name="maxInMemorySize" value="40960"/> </bean>
CommonsMultipartFile的常用方法
String getOriginalFilename():獲取上傳檔案的原名。
InputStream getInputStream():獲取檔案流。
void transferTo(File dest):將上傳檔案儲存到一個目錄檔案中。
<form action="/upload" enctype="multipart/form-data" method="post"> <input type="file" name="file"/> <input type="submit" value="upload"> </form>
package com.li.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.commons.CommonsMultipartFile; import javax.servlet.http.HttpServletRequest; import java.io.*; @Controller public class FileController { //@RequestParam("file") 將name=file控制元件得到的檔案封裝成CommonsMultipartFile 物件 //批量上傳CommonsMultipartFile則為陣列即可 @RequestMapping("/upload") public String fileUpload(@RequestParam("file") CommonsMultipartFile file ,HttpServletRequest request) throws IOException { //獲取檔名 : file.getOriginalFilename(); String uploadFileName = file.getOriginalFilename(); //如果檔名為空,直接回到首頁! if ("".equals(uploadFileName)){ return "redirect:/index.jsp"; } System.out.println("上傳檔名 : "+uploadFileName); //上傳路徑儲存設定 String path = request.getServletContext().getRealPath("/upload"); //如果路徑不存在,建立一個 File realPath = new File(path); if (!realPath.exists()){ realPath.mkdir(); } System.out.println("上傳檔案儲存地址:"+realPath); InputStream is = file.getInputStream(); //檔案輸入流 OutputStream os = new FileOutputStream(new File(realPath,uploadFileName));//檔案輸出流 //讀取寫出 int len=0; byte[] buffer = new byte[1024]; while ((len=is.read(buffer))!=-1){ os.write(buffer,0,len); os.flush(); } os.close(); is.close(); return "redirect:/index.jsp"; } }
採用file.Transto來儲存上傳的檔案
/* * 採用file.Transto 來儲存上傳的檔案 */ @RequestMapping("/upload2") public String fileUpload2(@RequestParam("file") CommonsMultipartFile file,HttpServletRequest request) throws IOException { //上傳路徑儲存設定 String path = request.getServletContext().getRealPath("/upload"); File realPath = new File(path); if (!realPath.exists()){ realPath.mkdir(); } //上傳檔案地址 System.out.println("上傳檔案儲存地址:"+realPath); //通過CommonsMultipartFile的方法直接寫檔案(注意這個時候) file.transferTo(new File(realPath +"/"+ file.getOriginalFilename())); return "redirect:/index.jsp"; }
檔案下載
1.設定response響應頭。
2.讀取檔案-InputStream。
3.寫出檔案-OutputStream。
4.執行操作。
5.關閉流。
@RequestMapping(value="/download") public String downloads(HttpServletResponse response ,HttpServletRequest request)throws Exception{ //要下載的圖片地址 String path = request.getServletContext().getRealPath("/upload"); String fileName = "基礎語法.jpg"; //1、設定response 響應頭 response.reset(); //設定頁面不快取,清空buffer response.setCharacterEncoding("UTF-8"); //字元編碼 response.setContentType("multipart/form-data"); //二進位制傳輸資料 //設定響應頭 response.setHeader("Content-Disposition", "attachment;fileName="+URLEncoder.encode(fileName, "UTF-8")); File file = new File(path,fileName); //2、 讀取檔案--輸入流 InputStream input=new FileInputStream(file); //3、 寫出檔案--輸出流 OutputStream out = response.getOutputStream(); byte[] buff =new byte[1024]; int index=0; //4、執行 寫出操作 while((index= input.read(buff))!= -1){ out.write(buff, 0, index); out.flush(); } out.close(); input.close(); return null; }
<a href="/download">點選下載</a>