Spring MVC的文件上傳和下載以及攔截器的使用實(shí)例
Spring MVC會(huì)根據(jù)請(qǐng)求方法的簽名不同,將請(qǐng)求消息中的信息以一定的方式轉(zhuǎn)換并綁定到請(qǐng)求方法的參數(shù)中。
1.文件上傳
文件上傳,必須將表單的method設(shè)置為POST,并將enctype設(shè)置為multipart/form-data。只有這樣,才能將文件的二進(jìn)制數(shù)據(jù)發(fā)送給服務(wù)器。
Spring 3.0規(guī)范提供了方法來處理文件上傳,但是這種上傳需要在Servlet中完成。而Spring MVC封裝了上傳功能,使用了Apache Commons FileUpload技術(shù)來實(shí)現(xiàn)了一個(gè)MultipartResolver實(shí)現(xiàn)類。
Spring MVC依賴的組件包
xml配置
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize"> <value>10485760</value> </property> <property name="defaultEncoding"> <value>UTF-8</value> </property> </bean>
后臺(tái)代碼
新建上傳FileModel
public class FileDataModel implements Serializable {
private String filename;
private MultipartFile file;
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public MultipartFile getFile() {
return file;
}
public void setFile(MultipartFile file) {
this.file = file;
}
}
Controller代碼
@Controller
@RequestMapping("file")
public class FileController {
@RequestMapping("upload")
public String upload() {
return "upload";
}
@RequestMapping(value = "upload", method = RequestMethod.POST)
public String uoload(FileDataModel fileDataModel, HttpServletRequest request, Model model) {
FileResult fileResult = new FileResult();
try {
if (fileDataModel.getFilename().isEmpty() || fileDataModel.getFile() == null)
throw new IllegalArgumentException("上傳文件名稱為空或者無上傳文件");
String filePath = request.getServletContext().getRealPath("/files");
String filename = fileDataModel.getFile().getOriginalFilename();
File savePath = new File(filePath, filename);
if (!savePath.getParentFile().exists())
savePath.getParentFile().mkdir();
fileDataModel.getFile().transferTo(new java.io.File(filePath + java.io.File.separator + filename));
fileResult.setTitle("上傳成功");
fileResult.setMessage("上傳成功");
fileResult.setSuccess(true);
} catch (Exception ex) {
fileResult.setTitle("上傳失??!");
fileResult.setMessage(ex.getMessage());
}
model.addAttribute("fileResult", fileResult);
return "fileresult";
}
}
前臺(tái)JSP頁面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Upload</title>
</head>
<body>
<form action="/file/upload" enctype="multipart/form-data" method="post">
<table>
<tr>
<td>文件描述:</td>
<td><input type="text" name="filename"/></td>
</tr>
<tr>
<td>請(qǐng)選擇文件:</td>
<td><input type="file" name="file"/></td>
</tr>
<tr>
<td>
<input type="submit" value="上傳"/>
</td>
</tr>
</table>
</form>
</body>
</html>
1.1Spring MVC的MultipartFile的常用方法
獲取文件數(shù)據(jù)
1.[] getBytes() throws IOException;
獲取文件的MIME類型,如image/jpeg等
2.String getContentType();
獲取文件流
3.InputStream getInputStream() throws IOException;
獲取表單中文件組件的名字
4.String getName();
獲取上傳文件的原名
5.String getOriginalFilename();
獲取文件的字節(jié)大小,單位為byte
6.long getSize();
是否有上傳的文件
7.boolean isEmpty();
將上傳文件保存到一個(gè)目標(biāo)文件中
8.void transferTo(File dest) throws IOException, IllegalStateException;
2.文件下載
Spring MVC提供了一個(gè)ResponseEntity類型,使用它可以很方便的定義返回的HttpHeader和HttpStatus
@RequestMapping("download")
public ResponseEntity<byte[]> download(HttpServletRequest request, @RequestParam("filename") String filename, Model model) {
ResponseEntity<byte[]> responseEntity = null;
try {
String path = request.getServletContext().getRealPath("/files");
String realPath = path + File.separator + filename;
File file = new File(realPath);
HttpHeaders headers = new HttpHeaders();
String downFileName = new String(filename.getBytes("UTF-8"), "iso-8859-1");
//通知瀏覽器以attachment(下載方式)打開圖片
headers.setContentDispositionFormData("attachment", downFileName);
//以二進(jìn)制流數(shù)據(jù)方式進(jìn)行下載
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
responseEntity = new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
} catch (Exception ex) {
ex.printStackTrace();
}
return responseEntity;
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>${requestScope.fileResult.title}</title>
</head>
<body>
<h1>${requestScope.fileResult.message}</h1><br/>
<a href="/file/download?filename=${requestScope.fileResult.fileName}" rel="external nofollow" >${requestScope.fileResult.fileName}</a>
</body>
</html>
3.攔截器
Interceptor攔截器是Spring MVC中相當(dāng)重要的功能,它的功能作用是攔截用戶的請(qǐng)求并進(jìn)行相對(duì)應(yīng)的處理。比如通過攔截器進(jìn)行用戶權(quán)限驗(yàn)證,或者判斷用戶是否已經(jīng)登錄等。
Spring MVC 攔截器是可插拔式的設(shè)計(jì)。如果需要使用某個(gè)攔截器,只需要在配置文件中應(yīng)用攔截器即可。
3.1 HandlerInterceptor接口
Spring MVC中的Interceptor攔截器請(qǐng)求是通過實(shí)現(xiàn)HandlerInterceptor接口來完成的。
3.2實(shí)現(xiàn)攔截器
1.自定義類實(shí)現(xiàn)Spring的HandlerInterceptor接口
重要接口
該請(qǐng)求方法將在請(qǐng)求處理之前被調(diào)用。這個(gè)方法的作用是對(duì)進(jìn)行調(diào)用方法前進(jìn)行一些前置初始化操作,進(jìn)行判斷用戶請(qǐng)求是否可以進(jìn)行下去。當(dāng)方法返回false的時(shí)候,后續(xù)的Interceptor及Controller都不會(huì)繼續(xù)執(zhí)行。
boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception;
該方法是在perHandle返回true時(shí),在調(diào)用目標(biāo)方法處理之后,在返回視圖之前調(diào)用。這時(shí)候我們可以針對(duì)Controller處理之后的ModelAndView對(duì)象進(jìn)行操作。
void postHandle( HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception;
該方法是在整個(gè)請(qǐng)求處理結(jié)束之后,也就是在DispatcherServlet渲染了對(duì)應(yīng)的視圖之后執(zhí)行。主要用于清理資源。
void afterCompletion( HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception;
2.自定義類繼承HandlerInterceptorAdapter
代碼演示
實(shí)現(xiàn)HandlerInterceptor
public class AuthorizationInterceptor implements HandlerInterceptor {
/**
* 不攔截用戶登錄頁面及注冊(cè)頁面
*/
private static final String[] IGNORE_URI = {"user/login", "user/signup"};
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
boolean flag = false;
String servletPath = request.getServletPath();
for (String url : IGNORE_URI) {
if (servletPath.contains(url)) {
flag = true;
break;
}
}
if (!flag) {
User user = (User) request.getSession().getAttribute("user");
if (user == null) {
request.setAttribute("message", "請(qǐng)先登錄再訪問網(wǎng)站");
request.getRequestDispatcher("user/login").forward(request, response);
} else
flag = true;
}
return flag;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
xml配置
<mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/home/index"/> <bean class="utils.AuthorizationInterceptor"/> </mvc:interceptor> </mvc:interceptors>
當(dāng)訪問home/index的時(shí)候需要進(jìn)行驗(yàn)證
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
淺談Java內(nèi)存模型之happens-before
于存在線程本地內(nèi)存和主內(nèi)存的原因,再加上重排序,會(huì)導(dǎo)致多線程環(huán)境下存在可見性的問題。那么我們正確使用同步、鎖的情況下,線程A修改了變量a何時(shí)對(duì)線程B可見?下面小編來簡單介紹下2019-05-05
SpringBoot+Echarts實(shí)現(xiàn)請(qǐng)求后臺(tái)數(shù)據(jù)顯示餅狀圖
這篇文章主要介紹了SpringBoot+Echarts實(shí)現(xiàn)請(qǐng)求后臺(tái)數(shù)據(jù)顯示餅狀圖,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-12-12
Spring Cloud Feign內(nèi)部實(shí)現(xiàn)代碼細(xì)節(jié)
Feign 的英文表意為“假裝,偽裝,變形”, 是一個(gè)http請(qǐng)求調(diào)用的輕量級(jí)框架,可以以Java接口注解的方式調(diào)用Http請(qǐng)求,而不用像Java中通過封裝HTTP請(qǐng)求報(bào)文的方式直接調(diào)用。接下來通過本文給大家分享Spring Cloud Feign內(nèi)部實(shí)現(xiàn)代碼細(xì)節(jié),感興趣的朋友一起看看吧2021-05-05
Spring Boot 3.4.0 結(jié)合 Mybatis-plus 實(shí)
本文詳細(xì)介紹了在 Spring Boot 3.4.0 項(xiàng)目中結(jié)合 Mybatis-plus 實(shí)現(xiàn)動(dòng)態(tài)數(shù)據(jù)源切換的完整方案,通過自定義注解和AOP切面,我們可以優(yōu)雅地實(shí)現(xiàn)方法級(jí)別的數(shù)據(jù)源切換,滿足多數(shù)據(jù)源場景下的各種需求,感興趣的朋友一起看看吧2025-04-04
詳解spring cloud config整合gitlab搭建分布式的配置中心
這篇文章主要介紹了詳解spring cloud config整合gitlab搭建分布式的配置中心,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-01-01
MyBatis傳入集合 list 數(shù)組 map參數(shù)的寫法
這篇文章主要介紹了MyBatis傳入集合 list 數(shù)組 map參數(shù)的寫法的相關(guān)資料,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2016-06-06

