上一章節對SpringMVC的表單驗證進行了詳細的介紹,本章節介紹SpringMVC文件的上傳和下載(重點),國際化以及異常處理問題。這也是SpringMVC系列教程中的最後一節,文章底部會提供該系列的源碼地址。
首先看效果圖(文件上傳,下載和異常處理)
css
pom.xml,文件上傳和下載是須要兩個jar包: commons-fileupload.jar 和 commons-io.jarhtml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.springmvc</groupId> <artifactId>springmvc</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <!-- 若不配置,打包時會提示錯誤信息 Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.3.2:compile (default-compile) on project springmvc: Compilation failure: 提示 未結束的字符串文字 ,若字符串後面加上空格後能夠打包成功,但會亂碼。 緣由是:maven使用的是默認的compile插件來進行編譯的。complier是maven的核心插件之一,然而complier插件默認只支持編譯Java 1.4 --> <build> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.7</source> <target>1.7</target> <encoding>UTF-8</encoding> </configuration> </plugin> </plugins> </build> <properties> <spring.version>4.1.3.RELEASE</spring.version> </properties> <dependencies> <!-- spring begin --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <!-- spring end --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> <!-- 缺乏則提示 javax.servlet.jsp.JspException cannot be resolved to a type --> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.2</version> <scope>provided</scope> </dependency> <!-- JSR 303 start --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>5.4.1.Final</version> </dependency> <dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>1.1.0.Final</version> </dependency> <!-- JSR 303 end --> <!-- 文件上傳 start --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> <!-- 文件上傳 end --> </dependencies> </project>
SpringMVC配置文件前端
<?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-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <!-- 配置自定掃描的包 --> <context:component-scan base-package="com.itdragon.springmvc" /> <!-- 配置視圖解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/"></property> <property name="suffix" value=".jsp"></property> </bean> <!-- 配置註解驅動 --> <mvc:annotation-driven /> <!-- 配置視圖 BeanNameViewResolver 解析器 使用視圖的名字來解析視圖 經過 order 屬性來定義視圖解析器的優先級, order 值越小優先級越高 --> <bean class="org.springframework.web.servlet.view.BeanNameViewResolver"> <property name="order" value="100"></property> </bean> <!-- 配置直接跳轉的頁面,無需通過Controller層 http://localhost:8080/springmvc/index 而後會跳轉到 WEB-INF/views/index.jsp 頁面 --> <mvc:view-controller path="/index" view-name="index"/> <mvc:default-servlet-handler/> <!-- 配置國際化資源文件 --> <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> <property name="basename" value="i18n"></property> </bean> <!-- 配置 SessionLocaleResolver 根據 Session 中特定屬性肯定本地化類型 必須將區域解析器的Bean名稱設置爲localeResolver,這樣DispatcherServlet才能自動偵測到它。 請注意,每DispatcherServlet只能註冊一個區域解析器。 * 第一步,把Locale對象設置爲Session屬性 * 第二步,從Session中獲取Locale對象給應用程序 --> <bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver"></bean> <!-- 配置 LocaleChangeInterceptor 從請求參數中獲取本次請求對應本地化類型 * 第一步,獲取name=locale的請求參數 * 第二步,把locale的請求參數解析爲Locale對象 * 第三步,獲取LocaleResolver對象 --> <mvc:interceptors> <bean id="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"></bean> </mvc:interceptors> <!-- 配置 CommonsMultipartResolver --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="UTF-8"></property> <property name="maxUploadSize" value="2048000"></property> </bean> <!-- 配置使用 SimpleMappingExceptionResolver 來映射異常 --> <bean id="simpleMappingExceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> <!-- 這裏是模型 exception --> <property name="exceptionAttribute" value="exception"></property> <property name="exceptionMappings"> <props> <!-- 若是是該異常,則跳轉到視圖 exception 頁面--> <prop key="java.lang.ArrayIndexOutOfBoundsException">exception</prop> </props> </property> </bean> </beans>
FileUploadController.java 文件上傳,下載和國際化知識點
國際化步驟
第一步,在SpringMVC配置文件中配置 SessionLocaleResolver(bean的id必須是localeResolver) 和 LocaleChangeInterceptor(bean放在mvc:interceptors 攔截器中)兩個bean。
第二步,視圖頁面引入 fmt 標籤,並用 <fmt:message key="xxx" /> 設置值。
第三步,語言切換的連接,其格式:English。
第四步,建立連接的目標方法,其參數爲Locale 類型參數。
第五步,準備語言文件,i18n_en_US.properties 和 i18n_zh_CN.properties,配置xxx的對應語言。java
文件上傳和下載
第一步,在SpringMVC配置文件中配置 CommonsMultipartResolver,並設置默認編碼格式和最大尺寸
第二步,視圖頁面建立一個form表單,並設置 enctype="multipart/form-data"
第三步,目標方法接收參數的類型爲 MultipartFile ,而後是文件流的操做。
第四步,看代碼吧!git
import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Locale; import java.util.Map; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.support.ResourceBundleMessageSource; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; @Controller public class FileUploadController { @Autowired private ResourceBundleMessageSource messageSource; /** * 國際化 * 第一步,在SpringMVC配置文件中,配置 SessionLocaleResolver 和 LocaleChangeInterceptor * 第二步,準備語言文件,i18n_en_US.properties 和 i18n_zh_CN.properties * 第三步,目標方法中,參數加入Locale對象。 */ @RequestMapping("/fileUpload") public String fileUpload(Locale locale) { // String val = messageSource.getMessage("file", null, locale); // System.out.println(val); return "fileUpload"; } // MultipartFile 上傳文件必用的變量類型 @RequestMapping("/testFileUpload") public String testFileUpload(@RequestParam("desc") String desc, @RequestParam("file") MultipartFile file, Map<String, Object> map, HttpServletRequest request) { InputStream in = null; OutputStream out = null; String fileName = file.getOriginalFilename(); // 獲取文件名 try { String realPath = request.getServletContext().getRealPath("uploads/"); in = file.getInputStream(); byte[] buffer = new byte[1024]; String filePath = realPath + "/" + fileName; // 文件上傳路徑 out = new FileOutputStream(filePath); int len = 0; while ((len = in.read(buffer)) != -1) { out.write(buffer, 0, len); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (null != out) { out.close(); } if (null != in) { in.close(); } } catch (IOException e) { e.printStackTrace(); } } map.put("fileName", fileName); return "fileUpload"; } // 不適合大文件的下載,適用於簡單的下載場景。 @RequestMapping("/downLoadFile") public ResponseEntity<byte[]> downLoadFile(@RequestParam("fileName") String fileName, HttpSession session) { byte [] body = null; ServletContext servletContext = session.getServletContext(); InputStream in = null; ResponseEntity<byte[]> response = null; try { in = servletContext.getResourceAsStream("/uploads/"+fileName); body = new byte[in.available()]; in.read(body); HttpHeaders headers = new HttpHeaders(); headers.add("Content-Disposition", "attachment;filename="+fileName); HttpStatus statusCode = HttpStatus.OK; response = new ResponseEntity<byte[]>(body, headers, statusCode); } catch (IOException e) { e.printStackTrace(); } finally { try { if (null != in) { in.close(); } } catch (IOException e) { e.printStackTrace(); } } return response; } }
fileUpload.jsp 文件上傳下載前端頁面web
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> <!DOCTYPE> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>SpringMVC 快速入門</title> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <div class="container"> <div class="row"> <div class="col-sm-6"> <div class="panel panel-info" style="margin-top:10px;"> <div class="panel-heading"> <h3 class="panel-title"><fmt:message key="file.upload" /></h3> </div> <div class="panel-body"> <!-- 缺乏 enctype="multipart/form-data" 會提示 org.springframework.web.multipart.MultipartException: The current request is not a multipart request --> <form action="${pageContext.request.contextPath }/testFileUpload" method="POST" enctype="multipart/form-data"> <div class="form-group"> <label class="col-sm-2 control-label"><fmt:message key="file" /></label> <div class="col-sm-10"> <input type="file" name="file" class="form-control" /> </div> </div> <div class="form-group"> <label class="col-sm-2 control-label"><fmt:message key="desc" /></label> <div class="col-sm-10"> <input type="text" name="desc" class="form-control" /> </div> </div> <input type="submit" value="Submit" class="btn btn-success" /> </form> <a href="fileUpload?locale=zh_CN" class="btn" >中文</a> <a href="fileUpload?locale=en_US" class="btn" >English</a> </div> </div> </div> <hr /> <a href="downLoadFile?fileName=${fileName}" >${fileName}</a> <hr /> </div> </div> </body> </html>
經常使用的三種異常處理
@ExceptionHandler 註解
第一步,建立一個用註解@ControllerAdvice 修飾的切面類(也能夠是普通類)。
第二步,建立一個目標方法,並用註解@ExceptionHandler 修飾,value值是一個數組,值是異常類。
第三步,目標方法的的參數必須有Exception 類型的參數,用於獲取運行時發生的異常。
第四步,目標方法若想把異常返回給頁面,能夠用ModelAndView 類型做爲返回值,而不能用Map做爲參數返回。spring
@ResponseStatus 註解
第一步,建立一個被註解@ResponseStatus 修飾的自定義異常類,value值是狀態碼,reason值是字符串。
第二步,在目標方法執行時拋出自定義異常。apache
SimpleMappingExceptionResolver Bean
第一步,在SpringMVC的配置文件中 配置Bean SimpleMappingExceptionResolver 。
第二步,設置exceptionAttribute 模型Model,必須和頁面上的值一致。
第三步,設置exceptionMappings 視圖View,只有當異常觸發時跳轉到視圖頁面。
注意細節,看代碼
StudyExceptionHandlerAdvice.java 切面類bootstrap
import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.servlet.ModelAndView; /** * 1 @ExceptionHandler 註解修飾的方法能夠放在普通類中,也能夠放在切面類中(@ControllerAdvice 註解修飾的類)。前者表示只處理當前類的異常,後者表示處理全局的異常。 * 2 @ExceptionHandler 註解修飾的方法參數中,不能有Map,不然會提示:。若但願把異常信息返回給前端,可使用ModelAndView * 3 @ExceptionHandler 註解修飾的多個方法中,優先級原則是就近原則(和異常精度越近的異常,優先執行)。 */ @ControllerAdvice public class StudyExceptionHandlerAdvice { @ExceptionHandler({ArithmeticException.class}) public ModelAndView handleArithmeticException(Exception exception){ System.out.println("ArithmeticException 出異常了: " + exception); ModelAndView mv = new ModelAndView("exception"); mv.addObject("exception", "ArithmeticException 出異常了: " + exception); return mv; } /*@ExceptionHandler({RuntimeException.class}) public ModelAndView handleRuntimeException(Exception exception){ System.out.println("RuntimeException 出異常了: " + exception); ModelAndView mv = new ModelAndView("exception"); mv.addObject("exception", "RuntimeException 出異常了: " + exception); return mv; }*/ }
ResponseStatusException.java 自定義異常類api
import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "ResponseStatusException : 自定義異常緣由") public class ResponseStatusException extends RuntimeException{ }
StudyExceptionController.java 異常處理測試類
import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; @Controller public class StudyExceptionController { @RequestMapping("/exception") public String exception(){ return "exception"; } @RequestMapping("/simpleMappingExceptionResolver") public String simpleMappingExceptionResolver(@RequestParam("num") int num){ String [] args = new String[10]; System.out.println("經過配置bean,來處理某一種異常致使的全部問題。" + args[num]); return "exception"; } @RequestMapping(value="/testResponseStatus") public String testResponseStatus(@RequestParam("num") Integer num){ System.out.println("@ResponseStatus 自定義異常"); if (0 == num) { throw new ResponseStatusException(); } return "exception"; } @RequestMapping("/testExceptionHandler") public String testExceptionHandler(@RequestParam("num") Integer num){ System.out.println("@ExceptionHandler - result: " + (10 / num)); return "exception"; } }
exception.jsp 異常處理前端頁面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>SpringMVC 快速入門</title> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <div class="container"> <div class="row"> <h2>SpringMVC 異常處理</h2> <hr/> @ExceptionHandler : <a href="testExceptionHandler?num=0" class="btn" >testExceptionHandler?num=0</a> <hr/> SimpleMappingExceptionResolver : <a href="simpleMappingExceptionResolver?num=20" class="btn" >simpleMappingExceptionResolver?num=20</a> <hr/> @ResponseStatus : <a href="testResponseStatus?num=0" class="btn" >testResponseStatus?num=0</a> <hr/> ${exception} </div> </div> </body> </html>
到這裏,SpringMVC的教程就結束了,有什麼好的建議和問題,能夠提出來。你們一塊兒成長!
SpringMVC源碼地址:https://gitee.com/itdragon/sp...