emStream> list = fileItems.get (fieldName);
if (list==null)
throw new IOException("No file item with name ''" + fieldName + "''.");
return list.get(0).openStream();
};
}
设计REST风格的MVC框架(13)
时间:2011-06-01 IBM 廖雪峰
对于正常的 Field 参数,保存在成员变量 Map<String, List<String>> formItems 中,通过覆写 getParameter()、 getParameters() 等方法,就可以让客户端把 MultipartHttpServletRequest 也当作一个普通的 Request 来操作,代码见清单 29。
清单 29. 覆写 getParameter
public class MultipartHttpServletRequest extends HttpServletRequestWrapper {
...
@Override
public String getParameter(String name) {
List<String> list = formItems.get(name);
if (list==null)
return null;
return list.get(0);
}
@Override
@SuppressWarnings("unchecked")
public Map getParameterMap() {
Map<String, String[]> map = new HashMap<String, String[]>();
Set<String> keys = formItems.keySet();
for (String key : keys) {
List<String> list = formItems.get(key);
map.put(key, list.toArray(new String[list.size ()]));
}
return Collections.unmodifiableMap(map);
}
@Override
@SuppressWarnings("unchecked")
public Enumeration getParameterNames() {
return Collections.enumeration(formItems.keySet());
}
@Override
public String[] getParameterValues(String name) {
List<String> list = formItems.get(name);
if (list==null)
return null;
return list.toArray(new String[list.size()]);
}
}
设计REST风格的MVC框架(14)
时间:2011-06-01 IBM 廖雪峰
为了简化配置,在 Web 应用程序启动的时候,自动检测当前 ClassPath 下 是否有 Commons FileUpload,如果存在,文件上传功能就自动开启,如果不存 在,文件上传功能就不可用,这样,客户端只需要简单地把 Commons FileUpload 的 jar 包放入 /WEB-INF/lib/,不需任何配置就可以直接使用。核 心代码见清单 30。
清单 30. 检测 Commons FileUpload
class Dispatcher {
private boolean multipartSupport = false;
...
void initAll(Config config) throws Exception {
try {
Class.forName ("org.apache.commons.fileupload.servlet.ServletFileUpload");
this.multipartSupport = true;
}
catch (ClassNotFoundException e) {
log.info("CommonsFileUpload not found.");
}
...
}
void handleExecution(Execution execution, HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
if (this.multipartSupport) {
if (MultipartHttpServletRequest.isMultipartRequest (request)) {
request = new MultipartHttpServletRequest (request,
|