spring mvc实现文件上传并携带其他参数的示例
程序员文章站
2024-03-06 14:25:14
这是主要使用到的jar 文件是:spring mvc +apache common-fileuplad
第一步:web.xml 文件。【重点是spring mvc的拦截器...
这是主要使用到的jar 文件是:spring mvc +apache common-fileuplad
第一步:web.xml 文件。【重点是spring mvc的拦截器和相关监听器】
<?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> <!-- 编码过滤器 --> <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监听器 --> <listener> <listener-class>org.springframework.web.context.contextloaderlistener</listener-class> </listener> <!-- 防止spring内存溢出监听器 --> <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,对应struts的后缀习惯 --> <url-pattern>/</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>/index.jsp</welcome-file> </welcome-file-list> </web-app>
第二步:spring-mvc 配置文件【重点:spring mvc 视图模式,spring mvc 文件上传限定参数,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"> <!-- 自动扫描该包,使springmvc认为包下用了@controller注解的类是控制器 --> <mvc:annotation-driven /> <mvc:default-servlet-handler/> <context:annotation-config/> <context:component-scan base-package="com" /> <!--避免ie执行ajax时,返回json出现下载文件 --> <bean id="mappingjacksonhttpmessageconverter" class="org.springframework.http.converter.json.mappingjacksonhttpmessageconverter"> <property name="supportedmediatypes"> <list> <value>text/html;charset=utf-8</value> </list> </property> </bean> <!-- 启动springmvc的注解功能,完成请求和注解pojo的映射 --> <bean class="org.springframework.web.servlet.mvc.annotation.annotationmethodhandleradapter"> <property name="messageconverters"> <list> <ref bean="mappingjacksonhttpmessageconverter" /> <!-- json转换器 --> </list> </property> </bean> <!-- 定义跳转的文件的前后缀 ,视图模式配置--> <bean class="org.springframework.web.servlet.view.internalresourceviewresolver"> <!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的url地址 --> <property name="prefix" value="/backstage/jsp/" /> <property name="suffix" value=".jsp" /> </bean> <!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 --> <bean id="multipartresolver" class="org.springframework.web.multipart.commons.commonsmultipartresolver"> <!-- 默认编码 --> <property name="defaultencoding" value="utf-8" /> <!-- 文件大小最大值 --> <property name="maxuploadsize" value="10485760000" /> <!-- 内存中的最大值 --> <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 页面
<%@ 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); //设置逻辑视图名,视图解析器会根据该名字解析到具体的视图页面 mv.setviewname("/users/users"); }else{ //用户存在 mv.addobject("partners", list); //设置逻辑视图名,视图解析器会根据该名字解析到具体的视图页面 mv.setviewname("/users/users"); } }catch(exception e){ //设置逻辑视图名,视图解析器会根据该名字解析到具体的视图页面 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); //如果只是上传一个文件,则只需要multipartfile类型接收文件即可,而且无需显式指定@requestparam注解 //如果想上传多个文件,那么 这里就要用multipartfile[]类型来接收文件,并且还要指定@requestparam注解 //并且上传多个文件时,前台表单中的所有<input type="file"/>的name都应该是myfiles,否则参数里的myfiles无法获取到所有上传的文件 for(multipartfile myfile : myfiles){ if(myfile.isempty()){ system.out.println("文件未上传"); }else{ system.out.println("文件长度: " + myfile.getsize()); system.out.println("文件类型: " + myfile.getcontenttype()); system.out.println("文件名称: " + myfile.getname()); system.out.println("文件原名: " + myfile.getoriginalfilename()); system.out.println("========================================"); //如果用的是tomcat服务器,则文件会上传到\\%tomcat_home%\\webapps\\yourwebproject\\web-inf\\upload\\文件夹中 string realpath = request.getsession().getservletcontext().getrealpath("/web-inf/upload"); //这里不必处理io流关闭的问题,因为fileutils.copyinputstreamtofile()方法内部会自动把用到的io流关掉,我是看它的源码才知道的 fileutils.copyinputstreamtofile(myfile.getinputstream(), new file(realpath, myfile.getoriginalfilename())); } } return "../../index"; } }
记得在web-info建立存放上传文件目录(upload)
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
上一篇: java结合WebSphere MQ实现接收队列文件功能
下一篇: 深入解析Java编程中的抽象类