javascript
SpringMVC的文件上传和拦截器
目錄
一、文件上傳
1.概述
2.案例1
3.案例2
二.攔截器
1.HandlerInterceptor接口
2.案例:攔截器實現用戶權限驗證
一、文件上傳
1.概述
-
SpringMVC會將上傳文件綁定到MultipartFile對象中。MultipartFile提供了獲取上傳文件內容、方法名等方法。通過transferTo()方法還可以將文件存儲到硬件中。
| byte[] getBytes() | 獲取文件數據 |
| String getContentType() | 獲取文件MIME類型,如image/jpeg等 |
| InputStream getInputStream() | 獲取文件流 |
| String getName() | 獲取表單中文件組件的名字 |
| String getOriginalFilename() | 獲取上傳文件的原名 |
| long getSize() | 獲取文件的字節大小 |
| boolean isEmpty() | 是否有上傳的文件 |
| void transferTo(File dest) | 將上傳文件保存到一個目標文件中 |
-
Spring MVC 上下文中默認沒有裝配 MultipartResovler,因此默認情況下不能處理文件的上傳工作,如果想使用 Spring 的文件上傳功能,需現在上下文中配置 MultipartResolver
2.案例1
uploadForm.jsp
?<form action="upload" enctype="multipart/form-data" method="post">用戶名:<input type="text" name="username"><br/>請上傳頭像:<input type="file" name="image"><br/><input type="submit" value="提交"></form>FileUploadController.java
? ?@RequestMapping("/upload")public String upload(HttpServletRequest request,@RequestParam("username") String username, @RequestParam("image") MultipartFile image, Model model) throws Exception {System.out.println(username);//如果文件不為空if (!image.isEmpty()) {//上傳文件路徑String path = request.getServletContext().getRealPath("/images");System.out.println("path:" + path);//上傳文件名String filename = image.getOriginalFilename();System.out.println("filename:" + filename);File filepath = new File(path, filename);//判斷路徑是否存在,如果不存在就創建一個if (!filepath.getParentFile().exists()) {filepath.getParentFile().mkdirs();}//將上傳文件保存到一個目標文件中image.transferTo(new File(path + File.separator + filename));//跳轉到下載頁面return "success";} else {return "error";}}dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xmlns:mvc="http://www.springframework.org/schema/mvc"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> ?<!-- 默認使用基于注釋的適配器和映射器 --><mvc:annotation-driven/><!-- 只把動態信息當做controller處理,忽略靜態信息 --><mvc:default-servlet-handler/><!--自動掃描包中的Controlller --><context:component-scan base-package="com.itheima.controller"/><!-- 配置視圖解析器: 如何把 handler 方法返回值解析為實際的物理視圖 --><bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="prefix" value="/WEB-INF/jsp/"/><!-- 前綴 --><property name="suffix" value=".jsp"/><!-- 后綴,自動拼接 --></bean> ?<!-- 配置 MultipartResolver --><bean id="multipartResolver"class="org.springframework.web.multipart.commons.CommonsMultipartResolver"><!-- 上傳文件大小上限 --><property name="defaultEncoding" value="UTF-8"></property><!-- 請求的編碼格式,必須和jsp的pageEncoding屬性一致 --><property name="maxUploadSize" value="1024000"></property></bean> </beans>3.案例2
FileUploadController.java
@Controller public class FileUploadController {@RequestMapping("/fileUpload")public String fileUpload(String picname, MultipartFile uploadFile, HttpServletRequest request) {System.out.println(uploadFile);//判斷是否上傳了文件if (!uploadFile.isEmpty()) {//上傳文件路徑//定義文件名String fileName = "";//獲取文件原始名String originalFilename = uploadFile.getOriginalFilename();System.out.println("originalFilename" + originalFilename);//截取文件拓展名String extendName = originalFilename.substring(originalFilename.lastIndexOf("." )+1);System.out.println("extendName:" + extendName);String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();//判斷用戶是否輸入了文件名if (!StringUtils.isEmpty(picname)) {fileName = uuid + "_" + picname + "." + extendName;} else {fileName = uuid + "_" + originalFilename;}//獲取文件路徑String path = request.getSession().getServletContext().getRealPath("/uploads");System.out.println(path);//解決一個文件夾目錄過多的問題//根據fileName計算出hashCode值int hashCode = fileName.hashCode();//生成兩級目錄int x = hashCode & 0xf;int y = hashCode & 0xf0 >> 4;File file = new File(path + File.separator + x + File.separator + y);System.out.println("file:"+file.getName());//判斷文件夾是否存在if (!file.exists()) {file.mkdirs();}try {//將上傳文件保存到一個目標文件中uploadFile.transferTo(new File(file, fileName));} catch (IOException e) {throw new RuntimeException(e);}}return "success";} }FileUpload.jsp
<form action="/fileUpload" method="post" enctype="multipart/form-data">名稱:<input type="text" name="picname"/><br/>圖片:<input type="file" name="uploadFile"/><br/><input type="submit" value="上傳"/></form> </body>二.攔截器
1.HandlerInterceptor接口
-
SpringMVC中的Interceptor攔截器攔截請求是通過實現HandlerInterceptor接口來完成的。若要自定義一個攔截器,只需要實現HandlerInterceptor接口或者繼承抽象類HandlerInterceptorAdapter。
-
HandlerInterceptor接口中定義了三個方法
| preHandle(request,response) | 在請求處理之前被調用 |
| postHandle(request,response) | 在Controller方法被調用之后,視圖返回渲染之前被調用 |
| afterCompletion(request,response) | 在視圖返回渲染之前被調用,一般用來資源清理 |
2.案例:攔截器實現用戶權限驗證
-
用戶必須登錄之后才可以訪問到網站首頁,如果沒有登錄,則跳轉到登陸頁面,并提示錯誤消息
loginForm.jsp
<font color="red">${requestScope.message}</font><br/> <form action="login" method="post"> 登錄名:<<input type="text" name="loginname" id="loginname"><br/> 密碼:<<input type="text" name="password" id="password"><br/> <input type="submit" value="登陸"> </form>UserController.java
? ?@RequestMapping("/{formName}")public String loginForm(@PathVariable String formName, Model model) {//model.addAttribute("user1",new User1());//動態跳轉頁面return formName;} ? ?@RequestMapping("/login")public ModelAndView login(String loginname, String password, ModelAndView modelAndView, HttpSession session){//模擬數據庫查找判斷是否有該用戶名及密碼if(loginname!=null&&loginname.equals("admin")&&password!=null&&password.equals("123456")){//模擬創建用戶Admin admin=new Admin(loginname,password);//登陸成功,將admin對象設置到HttpSession域對象中session.setAttribute("admin",admin);//轉發到main請求modelAndView.setViewName("redirect:main");}else{//登錄失敗,設置失敗信息,跳轉到登陸頁面modelAndView.addObject("message","用戶名或密碼錯誤"); ?modelAndView.setViewName("loginForm");}return modelAndView;} ?@RequestMapping("/main")public String main(Model model){//模擬數據庫獲得所有圖書List<Book> book_list=new ArrayList<>();book_list.add(new Book("Spring實戰",58));book_list.add(new Book("深入淺出MyBatis",69));book_list.add(new Book("java并發編程實戰",77));model.addAttribute("book_list",book_list);return "main";}main.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <c:forEach items="${requestScope.book_list}" var="book">${book.name}<br/>${book.price}<br/><hr/> </c:forEach>AuthorizationInterceptor.java
package com.itheima.interceptor;import com.itheima.domain.Admin; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView;import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;public class AuthorizationInterceptor implements HandlerInterceptor {//不攔截的請求private static final String[] IGNORE_URI={"/loginForm","/login"};@Overridepublic boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {boolean flag=false;String servletPath= httpServletRequest.getServletPath();//判斷請求是否需要攔截for (String s : IGNORE_URI) {if(servletPath.contains(s)){flag=true;break;}}if(!flag){//1.獲取session中的用戶Admin admin=(Admin)httpServletRequest.getSession().getAttribute("admin");//2.判斷用戶是否登陸if(admin==null){httpServletRequest.setAttribute("message","請先登錄");httpServletRequest.getRequestDispatcher("loginForm").forward(httpServletRequest,httpServletResponse);}else{flag=true;}}return flag;}@Overridepublic void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {System.out.println("postHandler...");}@Overridepublic void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {System.out.println("afterCompletion...");} }dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xmlns:mvc="http://www.springframework.org/schema/mvc"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"><!-- 默認使用基于注釋的適配器和映射器 --><mvc:annotation-driven/><!-- 只把動態信息當做controller處理,忽略靜態信息 --><mvc:default-servlet-handler/><!--自動掃描包中的Controlller --><context:component-scan base-package="com.itheima.controller"/><!-- 配置視圖解析器: 如何把 handler 方法返回值解析為實際的物理視圖 --><bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="prefix" value="/WEB-INF/jsp/"/><!-- 前綴 --><property name="suffix" value=".jsp"/><!-- 后綴,自動拼接 --></bean> <!-- SpringMVC攔截器定義--><mvc:interceptors><mvc:interceptor><!-- 攔截所有請求 --><mvc:mapping path="/**"/><!-- 用于指定排除的url --><!-- 還可以直接在配置文件中指定排除的url,不在攔截器中判斷<mvc:exclude-mapping path="/loginForm"/><mvc:exclude-mapping path="/login"/> --><bean class="com.itheima.interceptor.AuthorizationInterceptor"></bean></mvc:interceptor></mvc:interceptors>?
總結
以上是生活随笔為你收集整理的SpringMVC的文件上传和拦截器的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: jquery入门(一)
- 下一篇: javascript对象和json字符串