1.配置web.xmlcss
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <display-name></display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!-- 前端控制器 /=默認的url-pattern /a/b/c /a /a/d/c /a/d /a / *注意:此控制器默認加載/WEB-INF下的xxx-servlet.xml文件 :其中xxx等於【DispatcherServlet的配置名】 --> <servlet> <servlet-name>mvc62</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:mvc62.xml</param-value> </init-param> <!-- 隨項目啓動而啓動 --> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>mvc62</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 專治Post請求參數亂碼 --> <filter> <filter-name>encoding62</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <!-- 將請求的編碼方式設置爲utf-8 --> <init-param> <param-name>encoding</param-name> <param-value>utf-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encoding62</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
2.配置SpringMVC.xmlhtml
<?xml version="1.0" encoding="utf-8"?> <!-- xmlns:xml name space 是每個schema惟一標識 --> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd"> <!-- 掃描全部控制器中的註解 --> <context:component-scan base-package="com.c61.controller"></context:component-scan> <!-- MVC中基於註解開發,導入註解驅動 <mvc:annotation-driven/> --> <mvc:annotation-driven> <mvc:message-converters> <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <!-- 支持的格式:application/json --> <value>application/json</value> </list> </property> </bean> </mvc:message-converters> </mvc:annotation-driven> <!-- 視圖解析器:解析視圖 控制器方法的返回值,會被視圖解析器捕獲。"abc" 根據捕獲的內容,解析出一個視圖地址:/abc.jsp --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/"></property> <property name="suffix" value=".jsp"></property> </bean> <!-- 靜態資源:html,js,css,jpg 訪問404 解決 --> <mvc:default-servlet-handler/> <!-- 聲明異常處理器 --> <bean class="com.c61.ex.resolver.MyExceptionResolver"></bean> <!-- 攔截器配置 --> <!-- /a/b inter1 inter2 攔截順序:先配置先攔截 具體順序:pre1==pre2==contorller==post2==post1==after2==after1 --> <mvc:interceptors> <mvc:interceptor> <!-- 定義要攔截的路徑 /inter/* 匹配 /inter/a /inter/b inter/cssdafasfsafs 不能匹配/inter/a/b /inter/** 匹配 /inter/a /inter/xxsjaflsajf /inter/a/b/c/e/d/xxxcvx *注意:exclude-mapping不能單獨使用。要配合mapping使用 :在mapping匹配的範圍中排除一些個。 --> <mvc:mapping path="/inter/**"/> <mvc:mapping path="/a/b"/> <mvc:mapping path="/c/**"/> <mvc:exclude-mapping path="/inter/test/*"/> <mvc:exclude-mapping path="/c/b/**"/> <!-- 聲明攔截器 --> <bean class="com.c61.interceptor.MyInterceptor"/> </mvc:interceptor> <mvc:interceptor> <!-- 定義要攔截的路徑 --> <mvc:mapping path="/inter/test"/> <!-- 聲明攔截器 --> <bean class="com.c61.interceptor.MyInterceptor2"/> </mvc:interceptor> </mvc:interceptors> <!-- 聲明文件上傳解析器 注意:此解析器,id必須爲:multipartResolver --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 最大容許的上傳大小 byte --> <property name="MaxUploadSize" value="2097152"></property> </bean> <!-- 註冊,驗證碼生成器 --> <bean id="captcha" class="com.google.code.kaptcha.servlet.KaptchaExtend"> <constructor-arg> <props> <!-- 是否有邊框 邊框顏色 邊框粗細 --> <prop key="kaptcha.border">no</prop> <prop key="kaptcha.border.color">105,179,90</prop> <prop key="kaptcha.border.thickness">20</prop> <prop key="kaptcha.textproducer.font.color">black</prop> <prop key="kaptcha.image.width">200</prop> <prop key="kaptcha.image.height">50</prop> <prop key="kaptcha.textproducer.font.size">40</prop> <prop key="kaptcha.session.key">code61</prop> <prop key="kaptcha.textproducer.char.length">4</prop> <prop key="kaptcha.textproducer.font.names">Arial,Courier</prop> <!-- <prop key="kaptcha.background.clear.from">black</prop> <prop key="kaptcha.background.clear.to">255,0,0</prop> --> </props> </constructor-arg> </bean> </beans>
3.配置控制器前端
Class : UpLoadControllerjava
package com.c61.controller; import java.io.File; import java.io.IOException; import java.util.Map; import java.util.UUID; import javax.servlet.http.HttpSession; import org.apache.commons.io.FilenameUtils; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.multipart.MultipartFile; @Controller @RequestMapping("/up") public class UpLoadController { //經過MultipartFile接收文件 @RequestMapping("/test") public String testUP(MultipartFile file61,HttpSession s,Map m) throws IllegalStateException, IOException{ //file61.transferTo(new File("d:/abc/abc.txt")); //獲取虛擬路徑:/up61 對應部署到服務器後的具體的磁盤路徑 String realPath=s.getServletContext().getRealPath("/up61"); System.out.println("real:"+realPath); //獲取文件的後綴名 String extension=FilenameUtils.getExtension(file61.getOriginalFilename());//返回: jpg png pdf doc //獲取文件名 xxx.txt xxx.png //String fileName=file61.getOriginalFilename(); String fileName=UUID.randomUUID()+"."+extension; //拼接寫出路徑 String path=realPath+File.separator+fileName; System.out.println("File.separator:"+File.separator); file61.transferTo(new File(path)); //將圖片名稱存儲在Map中(Request) m.put("name",fileName); return "forward:/index.jsp"; } public static void main(String[] args) { //32長度 由16進制字符組成的全球惟一的字符串 UUID uuid=UUID.randomUUID(); System.out.println(uuid); } }
4.配置視圖web
View : upload.jspspring
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <div style="text-align: center;"> <form target="c61" method="post" enctype="multipart/form-data" action="${pageContext.request.contextPath}/up/test"> <input type="file" name="file61"/> <input type="submit" value="上傳"/> </form> <iframe name="c61" width="200px" height="200px" frameborder="0"></iframe> </div> </body> </html>
View : index.jspapache
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <img height="100px" width="100px" src="${pageContext.request.contextPath}/up61/${requestScope.name}"/> </body> </html>
Client : json
1>method="post" 2>enctype="multipart/form-data" <form method="post" enctype="multipart/form-data" action="${pageContext.request.contextPath}/up/test"> <input type="file" name="file61"/> <input type="submit" value="上傳"/> </form>
public String testUP(MultipartFile file61,HttpSession s) throws IllegalStateException, IOException{
//file61.transferTo(new File("d:/abc/abc.txt"));
//獲取虛擬路徑:/up61 對應部署到服務器後的具體的磁盤路徑
String realPath=s.getServletContext().getRealPath("/up61");
//獲取文件名 xxx.txt xxx.png
String fileName=file61.getOriginalFilename();
//拼接寫出路徑
String path=realPath+File.separator+fileName;
//將文件寫出到指定目錄位置
file61.transferTo(new File(path));
return "forward:/index.jsp";
}
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 最大容許的上傳大小 byte --> <property name="MaxUploadSize" value="2097152"></property> </bean> *ID必須爲:multipartResolver
//32長度 由16進制字符組成的全球惟一的字符串
UUID uuid=UUID.randomUUID();
System.out.println(uuid);
//uuid.toString()能夠做爲文件名使用,注意要拼接後綴
<!-- target="c61" 將響應展現在名爲c61的iframe中(再也不用一張新頁面承載響應) --> <form target="c61" method="post" enctype="multipart/form-data" action="${pageContext.request.contextPath}/up/test"> <input type="file" name="file61"/> <input type="submit" value="上傳"/> </form> <iframe name="c61" width="200px" height="200px" frameborder="0"></iframe>
啦啦啦spring-mvc