檔案上傳
1.添加jar包,maven中
dependency>
commons-fileupload
1.3.3
2.在springxml檔案中,設定上傳檔案的配置資訊
bean id="multipartResolver"
p:defaultEncoding="UTF-8"
p:maxUploadSize="10485760"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
切記 id一定要寫成上面的名字
public void upd(MultipartFile file1, String username, HttpServletRequest request) throws IOException {
byte b[] = file1.getBytes();
// 獲得檔案的運作路徑,及檔案的下載下傳名稱
File file = new File(request.getServletContext().getRealPath("WEB-INF/upload"), file1.getOriginalFilename());
FileOutputStream fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(b);
fileOutputStream.close();
}
下載下傳代碼
public void xia(MultipartFile file1, HttpServletResponse response) throws IOException {
//說明檔案路徑及檔案類型 及上傳的編碼格式
File file = new File("F:\\一些軟體\\壓縮包\\Keymaker-CORE(思維導圖).rar");
response.setContentType("application/x-rar-compressed");
response.setCharacterEncoding("UTF-8");
//得到父路徑名稱,進行替換的到子類的檔案名,并說明子類的檔案名格式
String name = file.getCanonicalPath();
name = name.replace(file.getParent() + "\\", "");
String filename = new String(name.getBytes(), "ISO-8859-1");
//将檔案名稱帶入到頭資訊中,并說明是下載下傳
response.setHeader("Content-Disposition", "attachment;filename=" + filename);
//從response中拿到outputStrem流
//用FileInputStream從檔案上讀上來 用outputStrem通過tcp進行傳輸
FileInputStream fileInputStream = new FileInputStream(file);
byte by[] = new byte[8 * 1024];
int leng;
OutputStream outputStream = response.getOutputStream();
while ((leng = fileInputStream.read(by)) != -1) {
outputStream.write(by, 0, leng);
outputStream.flush();
}
fileInputStream.close();
}
defaultServlet
因為mvc中靜态資源進行了攔截是以要在配置檔案中配置
!--優先級低 所有的類都沒找見他再去找-->
mvc:default-servlet-handler>
mvc:resources 資源配置
因為我們有時候需要将靜态資源放在WEB-INF下,當我們配置,外界就可以通路我們指定的 WEB-INF指定的夾子(好處打包可以将靜态資源打包進去)
mvc:resources mapping="/css/**" location="/WEB-INF/css/" />
//mapping 網絡通路路徑
//location 本地檔案夾路徑
攔截器就是對你的通路進行攔截(可以進行合法型判斷,登入做記錄,日志等操作),也可以在傳回參數的時候補參數
攔截器開發
1.寫一個普通類型實作接口 HandlerInterceptor
2.裡面有三個方法重寫
preHandle(action業務方法請求之前進行通路) 參數設定 true 繼續向下走 false 終止
下面兩個給力請求頭和響應頭 可以進行補參 等等操作
postHandle(action中的業務方法執行完畢後進行試圖渲染前的調用)
afterCompletion(視圖渲染後的調用)
3.配置檔案資訊
mvc:interceptors>
mvc:interceptor>
<mvc:mapping path="/admin/**"/>//網絡通路路徑
<mvc:exclude-mapping path="/admin/test2"/> 受到管理的對象
<bean class="com.kaige123.view.TestHandlerInterceptor"/>
</mvc:interceptor>