当list中只剩下最后一个菜品的时候,删除时报异常了
package com.food.servlet;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.food.bean.Food;
/**
* Servlet implementation class DeleteFoodServlet
*/
@WebServlet("/DeleteFoodServlet")
public class DeleteFoodServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
List<Food> foodList = (List<Food>) this.getServletContext().getAttribute("list");
String id = req.getParameter("id");
if (!foodList.isEmpty()) {
if (id != null && (!id.equals(""))) {
for (Food food : foodList) {
if (id.equals(food.getId())) {
foodList.remove(food);
}
}
this.getServletContext().setAttribute("list", foodList);
}
resp.sendRedirect("/FoodManager/showAllFood.jsp");
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(req, resp);
}
}<%@page import="org.apache.jasper.tagplugins.jstl.core.ForEach"%>
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@page import="com.food.bean.Food,java.util.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
<h3 align="center">菜品查询</h3>
<table border="1" align="center">
<tr>
<td>菜品id</td>
<td>菜名</td>
<td>口味</td>
<td>图片</td>
<td>价格</td>
<td>描述</td>
</tr>
<%
List<Food> foodList = (List) request.getServletContext().getAttribute("list");
if(foodList.size()!=0){
for (int i = 0; i < foodList.size(); i++) {
int index = foodList.get(i).getImg().lastIndexOf("\\");
String fileName = foodList.get(i).getImg().substring(index + 1);
%>
<tr>
<td><%=foodList.get(i).getId()%></td>
<td><%=foodList.get(i).getFoodName()%></td>
<td><%=foodList.get(i).getTaste()%></td>
<td><img src="/FoodManager/upload/<%=fileName%>" /></td>
<td><%=foodList.get(i).getPrice()%></td>
<td><%=foodList.get(i).getDescribe()%></td>
</tr>
<%
}}
%>
</table>
</body>
</html>0
收起
正在回答
2回答
建议同学不要在循环中删除,或删除后添加return语句,使其跳出方法,不再继续循环。
如果我的回答解决了你的疑惑,请采纳!祝学习愉快!
从网页搭建入门Java Web2018版
- 参与学习 人
- 提交作业 1088 份
- 解答问题 10204 个
如果你有Java语言基础,又想以后从事Java Web开发,那么本路径是你的不二选择!本路径从网页搭建开始入手,通过大量案例来学习Java Web基础。定能助你完成Java Web小白的蜕变!
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星