spring mvc實(shí)現(xiàn)文件上傳并攜帶其他參數(shù)的示例
這是主要使用到的jar 文件是:spring mvc +apache common-fileuplad
第一步:web.xml 文件?!局攸c(diǎn)是spring mvc的攔截器和相關(guān)監(jiān)聽(tīng)器】
<?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> <!-- Spring和mybatis的配置文件 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mybatis.xml</param-value> </context-param> <!-- 編碼過(guò)濾器 --> <filter> <filter-name>encodingFilter</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>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- Spring監(jiān)聽(tīng)器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 防止Spring內(nèi)存溢出監(jiān)聽(tīng)器 --> <listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener> <!-- Spring MVC servlet --> <servlet> <servlet-name>SpringMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>SpringMVC</servlet-name> <!-- 此處可以可以配置成*.do,對(duì)應(yīng)struts的后綴習(xí)慣 --> <url-pattern>/</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>/index.jsp</welcome-file> </welcome-file-list> </web-app>
第二步:spring-mvc 配置文件【重點(diǎn):spring mvc 視圖模式,spring mvc 文件上傳限定參數(shù),spring mvc 資源攔截管理和其他】
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <!-- 自動(dòng)掃描該包,使SpringMVC認(rèn)為包下用了@controller注解的類(lèi)是控制器 --> <mvc:annotation-driven /> <mvc:default-servlet-handler/> <context:annotation-config/> <context:component-scan base-package="com" /> <!--避免IE執(zhí)行AJAX時(shí),返回JSON出現(xiàn)下載文件 --> <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> </list> </property> </bean> <!-- 啟動(dòng)SpringMVC的注解功能,完成請(qǐng)求和注解POJO的映射 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="mappingJacksonHttpMessageConverter" /> <!-- JSON轉(zhuǎn)換器 --> </list> </property> </bean> <!-- 定義跳轉(zhuǎn)的文件的前后綴 ,視圖模式配置--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 這里的配置我的理解是自動(dòng)給后面action的方法return的字符串加上前綴和后綴,變成一個(gè) 可用的url地址 --> <property name="prefix" value="/backstage/jsp/" /> <property name="suffix" value=".jsp" /> </bean> <!-- 配置文件上傳,如果沒(méi)有使用文件上傳可以不用配置,當(dāng)然如果不配,那么配置文件中也不必引入上傳組件包 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 默認(rèn)編碼 --> <property name="defaultEncoding" value="utf-8" /> <!-- 文件大小最大值 --> <property name="maxUploadSize" value="10485760000" /> <!-- 內(nèi)存中的最大值 --> <property name="maxInMemorySize" value="40960" /> </bean> <!-- 聲明DispatcherServlet不要攔截下面聲明的目錄 --> <mvc:resources location="/js/" mapping="/js/**" /> <mvc:resources location="/images/" mapping="/images/**"/> <mvc:resources location="/css/" mapping="/css/**"/> <mvc:resources location="/common/" mapping="/common/**"/> </beans>
第三步:jsp 頁(yè)面
<%@ page language="java" pageEncoding="UTF-8"%> <form action="<%=request.getContextPath()%>/users/add" method="POST" enctype="multipart/form-data"> username: <input type="text" name="username"/><br/> nickname: <input type="text" name="nickname"/><br/> password: <input type="password" name="password"/><br/> yourmail: <input type="text" name="email"/><br/> yourfile: <input type="file" name="myfiles"/><br/> <input type="submit" value="添加新用戶"/> </form>
第四步:spring mvc 控制器代碼
package com.wlsq.controller; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.FileUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.ModelAndView; import com.wlsq.model.News; import com.wlsq.service.IUserMapperService; import com.wlsq.util.Pagination; @Controller @RequestMapping(value="/users") public class UserController { @Autowired private IUserMapperService userService; @RequestMapping(value="/userAll") public ModelAndView searchNews(HttpServletRequest request,HttpServletResponse response){ ModelAndView mv = null; try{ mv = new ModelAndView(); int pageSize = Integer .parseInt(request.getParameter("pageSize") == null ? "10" : request.getParameter("pageSize")); int pageNum = Integer .parseInt(request.getParameter("pageNum") == null ? "1" : request.getParameter("pageNum")); Map<String, Object> maps = new HashMap<>(); maps.put("pageSize", pageSize); maps.put("pageNum", (pageNum-1) * pageSize); List<News> list =userService.selectAllUsers(maps); int count = userService.selectCountUsers(); Pagination page = new Pagination(count); page.setCurrentPage(pageNum); mv.addObject("pnums", page.getPageNumList()); mv.addObject("currentPage", pageNum); mv.addObject("pnext_flag", page.nextEnable()); mv.addObject("plast_flag", page.lastEnable()); page.lastPage(); mv.addObject("last_page", page.getCurrentPage()); mv.addObject("count", count); mv.addObject("pageCount", page.getPages()); if(list !=null && list.size()>0){ //用戶存在 mv.addObject("partners", list); //設(shè)置邏輯視圖名,視圖解析器會(huì)根據(jù)該名字解析到具體的視圖頁(yè)面 mv.setViewName("/users/users"); }else{ //用戶存在 mv.addObject("partners", list); //設(shè)置邏輯視圖名,視圖解析器會(huì)根據(jù)該名字解析到具體的視圖頁(yè)面 mv.setViewName("/users/users"); } }catch(Exception e){ //設(shè)置邏輯視圖名,視圖解析器會(huì)根據(jù)該名字解析到具體的視圖頁(yè)面 mv.setViewName("/users/users"); } return mv; } @RequestMapping(value="/add", method=RequestMethod.POST) public String addUser(@RequestParam MultipartFile[] myfiles, HttpServletRequest request) throws IOException{ String username = request.getParameter("username"); String nickname = request.getParameter("nickname"); String password = request.getParameter("password"); String email = request.getParameter("email"); System.out.println("name:"+username); System.out.println("nickname:"+nickname); System.out.println("password:"+password); System.out.println("email:"+email); //如果只是上傳一個(gè)文件,則只需要MultipartFile類(lèi)型接收文件即可,而且無(wú)需顯式指定@RequestParam注解 //如果想上傳多個(gè)文件,那么 這里就要用MultipartFile[]類(lèi)型來(lái)接收文件,并且還要指定@RequestParam注解 //并且上傳多個(gè)文件時(shí),前臺(tái)表單中的所有<input type="file"/>的name都應(yīng)該是myfiles,否則參數(shù)里的myfiles無(wú)法獲取到所有上傳的文件 for(MultipartFile myfile : myfiles){ if(myfile.isEmpty()){ System.out.println("文件未上傳"); }else{ System.out.println("文件長(zhǎng)度: " + myfile.getSize()); System.out.println("文件類(lèi)型: " + myfile.getContentType()); System.out.println("文件名稱: " + myfile.getName()); System.out.println("文件原名: " + myfile.getOriginalFilename()); System.out.println("========================================"); //如果用的是Tomcat服務(wù)器,則文件會(huì)上傳到\\%TOMCAT_HOME%\\webapps\\YourWebProject\\WEB-INF\\upload\\文件夾中 String realPath = request.getSession().getServletContext().getRealPath("/WEB-INF/upload"); //這里不必處理IO流關(guān)閉的問(wèn)題,因?yàn)镕ileUtils.copyInputStreamToFile()方法內(nèi)部會(huì)自動(dòng)把用到的IO流關(guān)掉,我是看它的源碼才知道的 FileUtils.copyInputStreamToFile(myfile.getInputStream(), new File(realPath, myfile.getOriginalFilename())); } } return "../../index"; } }
記得在WEB-INFO建立存放上傳文件目錄(upload)
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Angular.js前臺(tái)傳list數(shù)組由后臺(tái)spring MVC接收數(shù)組示例代碼
- 詳解SpringMVC——接收請(qǐng)求參數(shù)和頁(yè)面?zhèn)鲄?/a>
- 解決angular的post請(qǐng)求后SpringMVC后臺(tái)接收不到參數(shù)值問(wèn)題的方法
- 詳解SpringMVC重定向傳參數(shù)的實(shí)現(xiàn)
- 學(xué)習(xí)SpringMVC——如何獲取請(qǐng)求參數(shù)詳解
- 詳解獲取Spring MVC中所有RequestMapping以及對(duì)應(yīng)方法和參數(shù)
- SpringMVC中使用bean來(lái)接收f(shuō)orm表單提交的參數(shù)時(shí)的注意點(diǎn)
- [Spring MVC]-詳解SpringMVC的各種參數(shù)綁定方式
- spring mvc中的@PathVariable獲得請(qǐng)求url中的動(dòng)態(tài)參數(shù)
- Spring MVC參數(shù)自動(dòng)綁定List的解決方法
相關(guān)文章
java實(shí)現(xiàn)國(guó)產(chǎn)sm4加密算法
這篇文章主要介紹了java實(shí)現(xiàn)國(guó)產(chǎn)sm4加密算法的步驟,幫助大家更好的理解和使用Java,感興趣的朋友可以了解下2020-12-12SpringBoot學(xué)習(xí)之全局異常處理設(shè)置(返回JSON)
本篇文章主要介紹了SpringBoot學(xué)習(xí)之全局異常處理設(shè)置(返回JSON),小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-02-02Android應(yīng)用開(kāi)發(fā)的一般文件組織結(jié)構(gòu)講解
這篇文章主要介紹了Android應(yīng)用開(kāi)發(fā)的一般文件組織結(jié)構(gòu)講解,同時(shí)附帶介紹了一個(gè)獲取Android的文件列表的方法,需要的朋友可以參考下2015-12-12Java NIO原理圖文分析及代碼實(shí)現(xiàn)
本文主要介紹Java NIO原理的知識(shí),這里整理了詳細(xì)資料及簡(jiǎn)單示例代碼和原理圖,有需要的小伙伴可以參考下2016-09-09Spring Boot中使用MongoDB的連接池配置的方法
本文介紹了Spring Boot中使用MongoDB的連接池配置的方法,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-03-03如何使用JFrame完成動(dòng)態(tài)模擬時(shí)鐘
本文介紹了如何使用JFrame完成動(dòng)態(tài)模擬時(shí)鐘,需要的朋友可以參考下2015-08-08