在學習SpringMvc的時候遇到了一個問題,後臺一直接收不到前臺傳遞過來的參數,耽誤了好長時間終於找到了緣由,寫篇博客記錄下這個坑,嚶嚶嚶 --__--web
使用SpringMvc接受前臺傳遞的參數很是簡單,只要參數名和前臺表單中的名稱一致便可,我弄得是一個文件上傳的例子,因此看下個人前臺頁面spring
<body> <!-- enctype="multipart/form-data"在文件上傳時加入,編碼類型,其值默認是application/x-www-form-urlencoded --> <form action="testFileUpload" method="post" enctype="multipart/form-data"> File: <input type="file" name="file" /> Desc: <input type="text" name="desc" /> <input type="submit" value="Submit" /> </form> <br><br> <a href="emps">List All Employees</a> </body>
下面是SpringMvc的控制器mvc
@Controller public class springMVCTest { @RequestMapping("/testFileUpload") public String testFileUpload(@RequestParam("desc") String desc, @RequestParam("file") MultipartFile file) throws IOException { System.out.println("desc: " + desc); System.out.println("originalFilename: " + file.getOriginalFilename()); System.out.println("inputStream: " + file.getInputStream()); return "success"; } }
接着是web.xml文件app
<!-- 配置DispatcherServlet --> <!-- SpringMvc會根據servlet-name配置,找到/WEB-INF/dispatcher-servlet.xml做爲配置文件載入Web工程中 --> <servlet> <servlet-name>springDispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springDispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
而後是SpringMvc的配置文件jsp
<!-- 配置自動掃描的包 --> <context:component-scan base-package="com.zgz.springmvc.crud"></context:component-scan> <context:component-scan base-package="com.zgz.springmvc.test"></context:component-scan> <!-- 配置視圖解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/"></property> <property name="suffix" value=".jsp"></property> </bean>
以後坑就來了,因爲是文件上傳,因此須要在Spring MVC的配置文件中添加multipartResolver,添加就添加唄,因而我就加上了下面這一段代碼:ide
<!-- 配置 MultipartResolver --> <bean id="commonsMultipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="UTF-8"></property> <property name="maxUploadSize" value="1024000"></property> </bean>
而後坑就出現,費盡周折發現是id寫錯了,id="multipartResolver",修改代碼爲:post
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="UTF-8"></property> <property name="maxUploadSize" value="1024000"></property> </bean>
附上我喜歡的一句話
我想也許有一天,你會變成像我這樣的老人,並向一位年輕人娓娓道來:你是如何將生活帶給你檸檬般的酸楚,釀成猶如檸檬汽水般的甘甜。學習