应用一:HttpServletRequestWrapper结合过滤器处理中文乱码
应用二:包装文件上传请求
目的:通过HttpServletRequestWrapper包装文件上传请求,模块化文件上传处理,提高代码复用率,简化开发。
文件上传采用的是commons-fileupload文件上传组件1.2.1版(同时需要commons-io-1.4.jar)。
考虑到将来有可能扩展支持其他上传组件,所以设计了以下两个接口,分别用于抽象请求处理和文件操作。
文件操作抽象层:
/**
* 之所以设计这个接口,是为了符合针对接口编程的设计原则,将来可以扩充支持其他上传组件的具体实现类型
*/
public interface FormFile {
/**
* 获得文件尺寸
*/
public long getFileSize();
/**
* 获得文件的名称
*/
public String getFileName();
/**
* 获得文件的字节数组形式的数据
*/
public byte[] getFileData()
throws FileNotFoundException, IOException;
/**
* 获得文件输入流
*/
public InputStream getInputStream()
throws FileNotFoundException, IOException;
/**
* 返回文件的类型,如“image/gif”,即“Content-Type”字段的值部分。
*/
public String getContentType();
/**
* 销毁上传文件
*/
public void destroy();
}
多媒体请求处理抽象层,用于解析请求,将文件参数封装成FormFile类型,保存在请求包装器中,稍后情看具体实现:
/**
* 处理文件上传请求
*/
public interface MultipartRequestHandler {
/**
* 解析文件上传请求
*/
public MultipartRequestWrapper handleRequest(HttpServletRequest request) throws ServletException;
}
接着来看针对commons-fileupload组件的FormFile实现。commons-fileupload组件将所有参数封装成FileItem类型,以List返回。所以这里通过包装FileItem对象来实现FormFile:
/**
* 针对commons-fileupload的FormFile实现,持有FileItem对象的引用,通过FileItem的方法实现 FormFile 的方法
*/
public class CommonsUploadFormFile implements FormFile {
FileItem fileItem;
InputStream inputstream;
//通过构造函数持有FileItem对象的引用
public CommonsUploadFormFile(FileItem fileItem) {
this.fileItem = fileItem;
}
public byte[] getFileData() throws FileNotFoundException, IOException {
return fileItem.get();
}
public String getFileName() {
return getBaseFileName(fileItem.getName());
}
public long getFileSize() {
return fileItem.getSize();
}
public InputStream getInputStream() throws FileNotFoundException,IOException {
return fileItem.getInputStream();
}
public String getContentType() {
return fileItem.getContentType();
}
public void destroy() {
fileItem.delete();
}
/**
* FileItem的getName()方法获得的是上传文件在客户机上存放的具体路径如:
* C:\Documents and Settings\shenlin\桌面\21534822.jpg