javascript
SpringMVC 刷课笔记
SpringMVC 筆記
一、Hello SpringMVC
原理圖(我們只需要做虛線部分,實現(xiàn)的Spring幫我們做了)
簡要分析執(zhí)行流程
- 我們假設(shè)請求的url為 : http://localhost:8080/SpringMVC/hello
- 如上url拆分成三部分:
- http://localhost:8080服務(wù)器域名.
- SpringMVC部署在服務(wù)器上的web站點.
- hello表示控制器
- 通過分析,如上url表示為:請求位于服務(wù)器localhost:8080上的SpringMVC站點的hello控制器。
項目目錄
1、 注冊:DispatcherServlet 這是SpringMVC的核心,請求分發(fā)器,前端控制器
web.xml
2、 配置 SpringMVC-Servlet.xml 文件
- 添加處理器映射
- 配置處理器適配器
- 添加視圖解析器
3、編寫 Controller
import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.Controller;import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;// 注意:這里先導(dǎo)入Controller接口 public class HelloController implements Controller {public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {// ModelAndView 模型和視圖ModelAndView mv = new ModelAndView();// 封裝對象 放在ModelAndView中,Modelmv.addObject("msg", "HelloSpringMVC");// 封裝要跳轉(zhuǎn)的視圖,放在ModelAndView中mv.setViewName("hello"); // : /WEB_INF/jsp/hello.jspreturn mv;} }4、 注冊到Spring容器中(SpringMVC-Servlet.xml 文件 )
<!-- Handler --><!-- BeanNameUrlHandlerMapping: bean --><bean id="/hello" class="com.example.controller.HelloController" />5、 啟動 Tomcat 測試
IDEA啟動Tomcat服務(wù)器,代碼無誤,但訪問出現(xiàn) 404 錯誤
快速生成:
二、使用注解開發(fā)
1、 注冊:DispatcherServlet 這是SpringMVC的核心,請求分發(fā)器,前端控制器 (與上文一樣)
2、 編寫spring配置文件(SpringMVC-Servlet.xml)
3、 編寫Controller類
import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping;@Controller public class HelloController {// 真實訪問的地址 項目名/HelloController/hello@RequestMapping("/hello")public String hello(Model model){// 封裝數(shù)據(jù)model.addAttribute("msg", "Hello, SpringMVC Annotation!");// 會被視圖解析器處理;return "hello"; // /WEB-INF/jsp/hello.jsp} }4、編寫jsp
5、啟動 Tomcat 測試
總結(jié):
Spring MVC 必須配置三大件:
處理器映射器、
處理器適配器、
<!-- 處理器適配器 --> <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter" />(通常我們只需要配置視圖解析器,處理器映射器和處理器適配器只需要開啟注解驅(qū)動即可,如下:)
<!--支持mvc注解驅(qū)動在Spring中一般采用 @RequestMapping 注解來完成映射關(guān)系要是 @RequestMapping 注解生效必須向上下文注冊 DefaultAnnotationHandlerMapping和一個 AnnotationMethodHandlerAdapter 實例這兩個實例分別在類級別和方法級別處理而 annotation-driven 配置幫助我們自動完成上述兩個實例的注入--><mvc:annotation-driven />視圖解析器
<!-- 視圖解析器:DispatcherServlet 給它的 ModelAndView1. 獲取 ModelAndView 中的數(shù)據(jù)2. 解析 ModelAndView 的視圖名字3. 拼接視圖名字,找到對應(yīng)的視圖 /WEB_INF/jsp/xxx.jsp4. 將數(shù)據(jù)渲染到這個視圖上--><bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver" ><!-- 前綴 --><property name="prefix" value="/WEB-INF/jsp/" /><!-- 后綴 --><property name="suffix" value=".jsp" /></bean>Controller
@Controller
用在類上代表這個類被Spring管理; 被這個注解的類中的所有方法,如果返回值是 String ,并且有具體的頁面可以跳轉(zhuǎn)就會被視圖解析器解析
RequestMapping
@RequestMapping
注解用于映射控制器類或者一個特定處理程序的方法,可用于類和方法上。用于類上表示所有響應(yīng)請求的方法都是改地址作為父路徑。
@RequestMapping(method = RequestMethod.xxx)
method屬性是對請求的method屬性的限定。指定必須通過xxx方法訪問。
RestFul風(fēng)格
RestFul就是一個資源定位及其資源操作的風(fēng)格,基于這個風(fēng)格設(shè)計可以更加簡潔,更有層次感,更易于實現(xiàn)緩存機制。
請求地址可以一樣,但是請求功能可以不同。
@PathVariable
URL -> /{變量名}使用@PathVariable(“變量名”)指定變量名(如果變量名和參數(shù)名一致也可以不指定),從而將URL中的值綁定到參數(shù)上。
@RequestMapping("/xxx/{a}/{xxx}") public String test(@PathVariable int a,@PathVariable("xxx") int b){}可以使用注解@(method名)Mapping來約束我們請求的類型,則不用定義@RequestMapping中的method屬性。如@GetMapping、@PostMapping、@DeleteMapping…
@GetMapping、@PostMapping 配置的地址都是:
http://localhost:8080/SpringMVC_04_controller/add/a/b但是按照提交的方式會走 @GetMapping 或 @PostMapping 標(biāo)記的方法
標(biāo)記@GetMapping注解的方法只用處理GET提交請求、通過@PostMapping注解的方法只能處理POST提交的請求…
重定向和轉(zhuǎn)發(fā)
- ModelAndView
設(shè)置ModelAndView對象,根據(jù)view,跳轉(zhuǎn)到指定頁面。
頁面 : {視圖解析器前綴} + viewName + {視圖解析器后綴}
通過SpringMVC 來實現(xiàn)那轉(zhuǎn)發(fā)和重定向 - 無視圖解析器
測試前,需要將視圖解析器的配置注釋掉。
轉(zhuǎn)發(fā):
return "/index.jsp"; return "forward:/index.jsp";重定向
return "redirect:/index.jsp";通過SpringMVC 來實現(xiàn)那轉(zhuǎn)發(fā)和重定向 - 有視圖解析器
重定向,不需要視圖解析器,本質(zhì)就是重新請求一個新地方,所以注意路徑問題。
可以重定向到另外一個請求實現(xiàn)。
轉(zhuǎn)發(fā):
return "test";重定向
return "redirect:/index.jsp"; // return "redirect:hello.do"; // hello.do 為另一個請求(路徑問題?)
接收請求參數(shù)以及數(shù)據(jù)回顯
- 請求參數(shù)
一般從前端傳遞的參數(shù)使用注解@RequestParam(“前端傳遞參數(shù)名”) 進行參數(shù)的命名,方便區(qū)分這是從前端傳遞的參數(shù)
- 數(shù)據(jù)回顯
- 第一種 ModelAndView
- 第二種 ModelMap
- 第三種 Model (大部分情況下使用)
Model:只有幾個適用于存儲數(shù)據(jù)的方法,簡化新手對Model 對象的操作和理解
ModelMap: 繼承了LinkMap,除了自身的一些方法外,同樣繼承LinkMap的方法和特性
ModelAndView: 可以存儲數(shù)據(jù)的同時,可以進行設(shè)置返回的邏輯視圖,進行控制視圖層的跳轉(zhuǎn)
亂碼問題
以前亂碼問題是通過過濾器解決,而SpringMVC給我們提供了一個過濾器,可以在 web.xml 中配置
<filter><filter-name>encoding</filter-name><filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class><init-param><param-name>encoding</param-name><param-value>utf-8</param-value></init-param> </filter> <filter-mapping><filter-name>encoding</filter-name><url-pattern>/*</url-pattern> </filter-mapping>JSON
JSON(JavaScript Object Notation, JS 對象簡譜) 是一種輕量級的數(shù)據(jù)交換格式。
采用獨立于編程語言的 文本格式 來存儲表示數(shù)據(jù)
有效提供網(wǎng)絡(luò)傳輸效率
前后端分離時代:
后端部署后端,提供接口,提供數(shù)據(jù) <<-- JSON -->> 前端獨立部署,負(fù)責(zé)渲染后端的數(shù)據(jù)
JavaScript代碼示例
// 編寫一個JavaScript對象 let user = {name: "面包",age: 18,sex: "男" }; console.log("user對象:", user);// 將 js 對象轉(zhuǎn)化為 json 對象 let json = JSON.stringify(user); console.log("json對象:", json);// 將 json 對象轉(zhuǎn)化為 js 對象 let obj = JSON.parse(json); console.log("obj對象:", obj);-
Jackson
導(dǎo)入依賴
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind --> <dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.11.2</version> </dependency>1、@ResponseBody // 他就不會走視圖解析器,會直接返回一個字符串
注解的作用是將controller的方法返回的對象通過適當(dāng)?shù)霓D(zhuǎn)換器轉(zhuǎn)換為指定的格式之后,寫入到response對象的body區(qū),通常用來返回JSON數(shù)據(jù)或者是XML數(shù)據(jù)。
注意:在使用此注解之后不會再走視圖處理器,而是直接將數(shù)據(jù)寫入到輸入流中,他的效果等同于通過response對象輸出指定格式的數(shù)據(jù)。
@ResponseBody是作用在方法上的,@ResponseBody 表示該方法的返回結(jié)果直接寫入 HTTP response body 中,一般在異步獲取數(shù)據(jù)時使用【也就是AJAX】。
注意:在使用 @RequestMapping后,返回值通常解析為跳轉(zhuǎn)路徑,但是加上 @ResponseBody 后返回結(jié)果不會被解析為跳轉(zhuǎn)路徑,而是直接寫入 HTTP response body 中。 比如異步獲取 json 數(shù)據(jù),加上 @ResponseBody 后,會直接返回 json 數(shù)據(jù)。@RequestBody 將 HTTP 請求正文插入方法中,使用適合的 HttpMessageConverter 將請求體寫入某個對象。
@RequestMapping("/login")@ResponseBodypublic User login(User user){return user;}/* 等價于 */@RequestMapping("/login")public void login(User user, HttpServletResponse response){response.getWriter.write(JSONObject.fromObject(user).toString());}2、@RequestBody
后端@RequestBody注解對應(yīng)的類在將HTTP的輸入流(含請求體)裝配到目標(biāo)類(即:@RequestBody后面的類)時,會根據(jù)json字符串中的key來匹配對應(yīng)實體類的屬性,
如果匹配一致且json中的該key對應(yīng)的值符合(或可轉(zhuǎn)換為)實體類的對應(yīng)屬性的類型要求時,會調(diào)用實體類的setter方法將值賦給該屬性。
3、@RestController
@RestController = @Controller + @ResponseBody組成
返回json數(shù)據(jù)不需要在方法前面加@ResponseBody注解了,
但使用@RestController這個注解,就不能返回jsp,html頁面,視圖解析器無法解析jsp,html頁面
標(biāo)注在類上,下面的所有方法只會返回接口的數(shù)據(jù)(前后端分離使用)
測試
public class User {private String name;private int age;private String sex;// getter and setter } @Controller public class UserController {@RequestMapping("/json1")@ResponseBody // 他就不會走視圖解析器,會直接返回一個字符串public String json1() throws JsonProcessingException {// jackson : ObjectMapperObjectMapper mapper = new ObjectMapper();User user = new User("面包1", 3, "男");String s = mapper.writeValueAsString(user);return s;}}發(fā)現(xiàn)有亂碼問題,我們需要設(shè)置一下他的編碼格式為utf-8,以及返回的類型
通過 @RequestMapping 的 produces 屬性來實現(xiàn),
亂碼問題統(tǒng)一解決
上一種方式比較復(fù)雜,可以使用Spring配置統(tǒng)一指定,這樣就不用每次都去處理
可以在SpringMVC配置文件中添加一段消息 StringHttpMassageConverter 轉(zhuǎn)換配置
<!-- JSON 亂碼 --> <mvc:annotation-driven><mvc:message-converters><bean class="org.springframework.http.converter.StringHttpMessageConverter" ><constructor-arg value="UTF-8" /></bean><bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" ><property name="objectMapper"><bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean"><property name="failOnEmptyBeans" value="false" /></bean></property></bean></mvc:message-converters> </mvc:annotation-driven>測試以及將JSON封裝成工具類
@RestController public class UserController {@RequestMapping("json2")public String json2() throws JsonProcessingException {ObjectMapper mapper = new ObjectMapper();List<User> users = new ArrayList<User>();for (int i = 1; i < 5; i++) {User user = new User("面包"+i+"號", i, "男");users.add(user);}String str = mapper.writeValueAsString(users);return str;}@RequestMapping("json3")public String json3() throws JsonProcessingException {ObjectMapper mapper = new ObjectMapper();// 不使用時間戳的方式mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);// 自定義時間日期格式方式SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");// 指定日期格式mapper.setDateFormat(dateFormat);Date date = new Date();// ObjectMapper : 時間解析后的默認(rèn)格式為Timestamp(時間戳)return mapper.writeValueAsString(date);}@RequestMapping("json4")public String json4() throws JsonProcessingException {Date date = new Date();String df = "YYYY-MM-dd HH:mm:ss";return JsonUtils.getJson(date, df);}} public class JsonUtils {public static String getJson(Object object){return getJson(object, "YYYY-MM-dd HH:mm:ss");}public static String getJson(Object object, String dataFormat){ObjectMapper mapper = new ObjectMapper();// 不使用時間戳的方式mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);// 自定義時間日期格式方式SimpleDateFormat sdf = new SimpleDateFormat(dataFormat);// 指定日期格式mapper.setDateFormat(sdf);try {return mapper.writeValueAsString(object);} catch (JsonProcessingException e) {e.printStackTrace();}return null;} }-
FastJson (阿里開源)
導(dǎo)入依賴
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson --> <dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.73</version> </dependency>FastJson 三個主要的類
-
JSONObject 代表 JSON 對象
- JSONObject 實現(xiàn)了 Map 接口,猜想 JSONObject 底層操作是由 Map 實現(xiàn)的。
- JSONObject 對應(yīng) json對象,通過各種形式的get()方法可以獲取json對象中的數(shù)據(jù),也可以利用諸如size(),isEmpty()
等方法獲取 “鍵:值” 對的個數(shù)和判斷是否為空,其本質(zhì)是調(diào)用Map接口并調(diào)用接口中的方法實現(xiàn)。
-
JSONArray 代表 JSON 數(shù)組
-
JSON 代表 JSONObject 和 JSONArray 的轉(zhuǎn)變
代碼示例
@RestController @RequestMapping("/fastJson") public class UserController2 {@RequestMapping("/json1")public String test1(){List<User> userList = new ArrayList<User>();User user = null;for (int i = 1; i < 5; i++) {user = new User("面包"+i+"號", i, "男");userList.add(user);}// Java 裝對象 轉(zhuǎn) JSON 字符串String str1 = JSON.toJSONString(userList);System.out.println("JSON.toJSONString(userList) ==> " + str1);String str2 = JSON.toJSONString(user);System.out.println("JSON.toJSONString(user) ==> " + str2);// JSON 字符串 轉(zhuǎn) Java 對象User json_to_user = JSON.parseObject(str2, User.class);System.out.println("JSON.parseObject(str2, User.class) ==> " + json_to_user);// Java 對象 轉(zhuǎn) JSON 對象JSONObject jsonObject = (JSONObject) JSON.toJSON(user);System.out.println("(JSONObject) JSON.toJSON(user) ==> " + jsonObject.toJSONString());return str1 + str2 + json_to_user.toString() + jsonObject.toJSONString();}}AJAX
Ajax 即“Asynchronous Javascript And XML”(異步 JavaScript 和 XML),是指一種創(chuàng)建交互式、快速動態(tài)網(wǎng)頁應(yīng)用的網(wǎng)頁開發(fā)技術(shù),無需重新加載整個網(wǎng)頁的情況下,能夠更新部分網(wǎng)頁的技術(shù)。
通過在后臺與服務(wù)器進行少量數(shù)據(jù)交換,Ajax 可以使網(wǎng)頁實現(xiàn)異步更新。這意味著可以在不重新加載整個網(wǎng)頁的情況下,對網(wǎng)頁的某部分進行更新。
測試
@RestController public class AjaxController {@RequestMapping("/t1")public String test(){return "Hello";}@RequestMapping("/a")public void a(String name, HttpServletResponse response) throws IOException {System.out.println("a:param => " + name);if ("mianbao".equals(name)){response.getWriter().print("true");}else{response.getWriter().print("false");}}@RequestMapping("/a2")public List<User> a2(){List<User> userList = new ArrayList<User>();userList.add(new User("面包1", 1, "男"));userList.add(new User("面包2", 2, "女"));userList.add(new User("面包3", 3, "男"));return userList;}} <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head><title>$Title$</title><script src="${pageContext.request.contextPath}/static/js/jquery-3.4.1/jquery-3.4.1.js"></script><script type="text/javascript">function a() {$.post({url: "${pageContext.request.contextPath}/a",data: {"name": $("#username").val()},success: function (res) {alert(res);}});}</script> </head> <body><%-- 失去焦點的時候,發(fā)起一個請求到后端 --%>用戶名:<input type="text" id="username" onblur="a()" /> </body> </html> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head><title>Title</title><script src="${pageContext.request.contextPath}/static/js/jquery-3.4.1/jquery-3.4.1.js"></script><script type="text/javascript">$(function () {$("#btn").click(function (e) {$.post("${pageContext.request.contextPath}/a2", function (res) {console.log(res);let html = "";for (let i = 0; i < res.length; i++) {html += "<tr>" +"<td>" + res[i].name + "</td>" +"<td>" + res[i].age + "</td>" +"<td>" + res[i].sex + "</td>" +"</tr>"}$("#content").html(html);});})});</script> </head> <body><input type="button" value="加載數(shù)據(jù)" id="btn" > <table><tr><td>姓名</td><td>年齡</td><td>性別</td></tr><tbody id="content"><%-- 數(shù)據(jù): 后臺 --%></tbody> </table></body> </html>Ajax 驗證用戶名體驗
@RequestMapping("/a3")public String a3(String name, String pwd){String msg = "";if (name != null){if ("admin".equals(name)){msg = "ok";}else{msg = "用戶名有誤";}}if (pwd != null){if ("admin".equals(pwd)){msg = "ok";}else{msg = "密碼名有誤";}}return msg;} <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head><title>登錄</title><script src="${pageContext.request.contextPath}/static/js/jquery-3.4.1/jquery-3.4.1.js"></script><script type="text/javascript">function a1() {$.post({url: "${pageContext.request.contextPath}/a3",data: {"name": $("#name").val()},success: function (res) {console.log(res);if (res.toString() === "ok"){$("#nameInfo").css("color", "green");}else{$("#nameInfo").css("color", "red");}$("#nameInfo").html(res);}});}function a2() {$.post({url: "${pageContext.request.contextPath}/a3",data: {"pwd": $("#password").val()},success: function (res) {console.log(res);if (res.toString() === "ok"){$("#pwdInfo").css("color", "green");}else{$("#pwdInfo").css("color", "red");}$("#pwdInfo").html(res);}});}</script></head> <body><p>用戶名: <input type="text" id="name" onblur="a1()"><span id="nameInfo"></span> </p> <p>密碼: <input type="password" id="password" onblur="a2()"><span id="pwdInfo"></span> </p></body> </html>攔截器
攔截器(Interceptor),主要完成請求參數(shù)的解析、將頁面表單參數(shù)賦給值棧中相應(yīng)屬性、執(zhí)行功能檢驗、程序異常調(diào)試等工作。
Spring MVC 中的攔截器就類似于 Servlet開發(fā)中的過濾器Filter,用于處理器進行預(yù)處理和后處理。開發(fā)者可以自己定義攔截器來實現(xiàn)特定的功能。
過濾器和攔截器的區(qū)別: 攔截器是 AOP 思想的具體應(yīng)用。
- 攔截器是 SpringMVC 框架自己的,只有使用了 SpringMVC 框架的工程才能使用。
- 攔截器只會攔截訪問的控制方法,如果訪問的是 jsp/html/css/js/image 是不進行攔截的。
自定義攔截器
想要實現(xiàn)攔截器,必須實現(xiàn) HandlerInterceptor 接口.
編寫攔截器類:
public class MyInterceptor implements HandlerInterceptor {// 在請求處理的方法之前執(zhí)行// 如果返回 true 執(zhí)行下一個攔截器// 如果返回 false 就不執(zhí)行下一個攔截器public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {System.out.println("===================處理前======================");return true;}// 在請求處理方法執(zhí)行之后執(zhí)行 (日志)public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {System.out.println("===================處理后======================");}// 在 DispatcherServlet 處理后執(zhí)行, 做清理工作public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {System.out.println("===================清理======================");} }Spring 配置文件配置攔截器:
<!-- 攔截器配置 --> <mvc:interceptors><mvc:interceptor><!-- /** -> 包括這個請求下面的所有請求 --><mvc:mapping path="/**"/><bean class="com.example.interceptor.MyInterceptor" /></mvc:interceptor> </mvc:interceptors>實現(xiàn)登錄攔截器…
SpringMVC 文件上傳和下載
SpringMVC 上下文中默認(rèn)沒有裝配 MultipartResolver, 因此默認(rèn)情況下不能處理文件上傳工作。
如果需要使用 Spring 的文件上傳功能,則需要在上下文中配置 MultipartResolver。
前端表單需求: 為了能夠上傳文件,必須將表單的 method 設(shè)置為 POST 方式,并將 enctype 設(shè)置為
multipart/form-data。只有在這樣的情況下,瀏覽器才會將用戶選擇的文件以二進制數(shù)據(jù)發(fā)送給服務(wù)器。
一、導(dǎo)入.jar 包
文件上傳的jar包:commons-fileupload.jar 和 commons-io.jar 包:
<!-- https://mvnrepository.com/artifact/commons-io/commons-io --> <dependency><groupId>commons-io</groupId><artifactId>commons-io</artifactId><version>2.4</version> </dependency> <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload --> <dependency><groupId>commons-fileupload</groupId><artifactId>commons-fileupload</artifactId><version>1.3.3</version> </dependency> <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api --> <dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>4.0.1</version><scope>provided</scope> </dependency>二、配置bean: MultipartResolver
【!!!注意: 這個 bean 的 id 必須為:multipartResolver, 否則上傳文件會報 400 錯誤】
<!-- 文件上傳的配置 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"><!-- 請求的編碼格式,必須和 JSP 的 pageEncoding 屬性一致,以便正確讀取表單的內(nèi)容,默認(rèn)為 ISO-8859-1 --><property name="defaultEncoding" value="utf-8" /><!-- 文件上傳的大小限制,單位為字節(jié),(10485760=10M) --><property name="maxUploadSize" value="10485760" /><property name="maxInMemorySize" value="40960" /> </bean>CommonsMultipartResolver 常用方法:
String getOriginalFilename() : 獲取上傳文件原名
InputStream getInputStream() : 獲取文件流
void transferTo(File dest) : 將上傳文件保存到一個目錄中
文件上傳
編寫前端頁面
<form action="" method="post" enctype="multipart/form-data"><input type="file" name="file"><input type="submit" value="上傳"></form>編寫Controller
- 方式一
- 方式二
測試
…
文件下載
代碼實現(xiàn):
@RequestMapping("/downloa")public String download(HttpServletRequest request, HttpServletResponse response) throws IOException {// 要下載的圖片地址String path = request.getServletContext().getRealPath("/upload");String fileName = "test.jpg";// 1. 設(shè)置 response 響應(yīng)頭response.reset(); // 設(shè)置頁面不緩存,清空 bufferresponse.setCharacterEncoding("UTF-8"); // 字符編碼response.setContentType("multipart/form-data"); // 以二進制的方式傳輸數(shù)據(jù)// 設(shè)置響應(yīng)頭response.setHeader("content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));File file = new File(path, fileName);// 2. 讀取文件 -> InputStreamInputStream is = new FileInputStream(file);// 3. 寫出文件 -> OutputStreamOutputStream out = response.getOutputStream();int len = 0;byte[] buffer = new byte[1024];// 4. 執(zhí)行寫出操作while ((len = is.read(buffer)) != -1){out.write(buffer, 0, len);out.flush();}// 5. 關(guān)閉流out.close();is.close();return null;}總結(jié)
以上是生活随笔為你收集整理的SpringMVC 刷课笔记的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: OpenCV图像处理----图像的二值化
- 下一篇: Java开发使用百度翻译api