springMVC实现文件上传:
springMVC上传文件和Servlet方式本质是一样的:都是通过commons-fileupload.jar和commons-io.jar
但springMVC可以简化文件上传的代码,但必须满足条件:实现CommonsMultparResolver接口。
具体步骤:
①导入以下两个jar包:
commons-fileupload.jar
commons-io.jar
②配置XML:CommonsMultiparResolver:
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"></property>
<!-- 上传文件的最大值 单位byte 如果-1表示无限制-->
<property name="maxUploadSize" value="102400"></property>
</bean>
③controller处理方法:
//文件上传处理方法
@RequestMapping(value="testUpload")
public String testUpload(@RequestParam("desc")String desc,@RequestParam("file")MultipartFile file) throws IOException {
System.out.println("文件描述信息:"+desc);
//jsp中的文件上传:file
InputStream input = file.getInputStream();
//上传时候的名字
String fileName = file.getOriginalFilename();
OutputStream out = new FileOutputStream("d:\\"+fileName);
byte[] bs = new byte[1024];
int len = -1;
while((len = input.read(bs))!=-1) {
out.write(bs,0,len);
}
out.close();
input.close();
//将file上传到服务器中的某一个硬盘中
return "success";
}
④前端编写上传按钮:
<form action="springMVCHandler/testUpload" method="post" enctype="multipart/form-data">
<input name="file" type="file"/>
描述 :<input name="desc" type="text"/>
<input type="submit" value="上传">
</form>
springMVC拦截器的使用
拦截器的原理和过滤器相同
springMVC:要想实现拦截器,必须实现一个接口HandlerIntercept
①编写拦截器implements HandlerInterceptor
package org.gduf.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
public class MyInterceptor {
public boolean preHandle(HttpServletRequest request,HttpServletResponse response) throws Exception{
System.out.println("拦截请求"); //
return true;//true:拦截操作之后,放行。false:拦截之后不放行,请求终止
}
public void postHandle(HttpServletRequest request,HttpServletResponse response)throws Exception {
System.out.println("拦截响应");
}
public void afterCompletion(HttpServletRequest request,HttpServletResponse response)throws Exception{
System.out.println("视图(jsp)被渲染完毕");
}
}
②配置:将自己写的拦截器,配置到springmbc中(spring)
<!-- 将自己写的拦截器 配置到springmbc中(spring)默认拦截全部请求 -->
<mvc:interceptors>
<mvc:interceptor>
<!-- 指定拦截的路径,取交集,基于ant风格 -->
<mvc:mapping path="/**"/>
<!-- 指定不拦截的路径 -->
<mvc:exclude-mapping path="/handler/testUpload"/>
<bean class="org.gduf.interceptor.MyInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
设置:
<mvc:mapping path="/**"/>
每次调用到controller的时候救护hi请求拦截器。同样拦截器可以配置多个只需多写个类,而且多配个
<mvc:interceptors>
<mvc:interceptor>
<!-- 指定拦截的路径,取交集,基于ant风格 -->
<mvc:mapping path="/**"/>
<!-- 指定不拦截的路径 -->
<mvc:exclude-mapping path="/handler/testUpload"/>
<bean class="org.gduf.interceptor.MySecondInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
就可以了!!!