正在回答
2回答
如果把数据都封装到food中,就不用再存储到params中了。所以如果你用集合写了,可以就不用Food类了,如果用Food类的话,整个结构确实需要改一下,FoodDaoImpl类中的List存储的就应该都是Food类的对象。
关于覆盖的问题,建议你把添加菜品相关的代码贴出来,帮你看看。
祝学习愉快!
驱车上东门
2018-03-25 09:02:37
public class UploadUtils {
public static Map<String, Object> params = new HashMap<>();
public static String getUUIDFileName(String fileName) {
int idx = fileName.lastIndexOf(".");
String extention = fileName.substring(idx);
String uuidFileName = UUID.randomUUID().toString().replace("-", "") + extention;
return uuidFileName;
}
public static Map<String, Object> UploadFile(HttpServletRequest request, String uploadDirectory)
throws IOException {
DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
List<FileItem> items = null;
try {
items = servletFileUpload.parseRequest(request);
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Map<String, String> map = new HashMap<>();
String url = null;
for (FileItem item : items) {
if (item.isFormField()) {
String name = item.getFieldName();
String value = item.getString("UTF-8");
map.put(name, value);
} else {
String fileName = item.getName();
if (fileName != null && !fileName.equals("")) {
fileName = getUUIDFileName(fileName);
// 获得文件上传的路径
String path = uploadDirectory;
url = path + "\\" + fileName;
InputStream is = item.getInputStream();
OutputStream os = new FileOutputStream(url);
int len = 0;
byte[] b = new byte[1024];
while ((len = is.read(b)) != -1) {
os.write(b, 0, len);
}
is.close();
os.close();
}
}
}
params.put("id",map.get("id"));
params.put("foodName",map.get("foodName"));
params.put("taste",map.get("taste"));
params.put("foodImage",url);
params.put("price",map.get("price"));
params.put("description",map.get("description"));
return (Map<String, Object>) params;
}
}
public class FoodAddServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String uploadDirector = this.getServletContext().getRealPath("/upload");
UploadUtils upload = new UploadUtils();
FoodDaolmpl add = new FoodDaolmpl();
add.addFood(upload.UploadFile(request, uploadDirector));
response.sendRedirect(request.getContextPath() + "/showFoodList.jsp");
}
从网页搭建入门Java Web2018版
- 参与学习 人
- 提交作业 1088 份
- 解答问题 10204 个
如果你有Java语言基础,又想以后从事Java Web开发,那么本路径是你的不二选择!本路径从网页搭建开始入手,通过大量案例来学习Java Web基础。定能助你完成Java Web小白的蜕变!
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星