根据菜名查询不出
1.package com.imooc.domain;
import java.util.ArrayList;
import java.util.List;
public class FoodDaoImpl {
private static final List<Food> db = new ArrayList<Food>();
/**
* 添加菜品
* @param food
*/
public void addFood(Food food) {
db.add(food);
}
/**
* 查询所有菜品信息
* @return
*/
public List<Food> getAllFood() {
return db;
}
/**
* 根据菜品名称查询菜品信息
* @param foodName
* @return
*/
public Food getFoodByName(String foodName) {
return null;
}
/**
* 根据菜品id查询菜品信息
* @param id
* @return
*/
public Food getFoodById(String id) {
return null;
}
/**
* 菜品修改
* @param newFood
*/
public void updateFood(Food newFood) {
}
/**
* 根据菜品id进行删除
* @param id
*/
public void deleteFoodById(String id) {
}
}
2.package com.imooc.servlet;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
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 org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import com.imooc.domain.Food;
import com.imooc.domain.FoodDaoImpl;
import com.imooc.utils.UploadUtils;
/**
* Servlet implementation class FoodAddServlet
*/
@WebServlet("/FoodAddServlet")
public class FoodAddServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
//定义一个Map集合用于保存接受到的数据
Map<String,String> map = new HashMap<String,String>();
//1.创建一个磁盘文件项工厂对象
DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
//2.创建一个核心解析类
ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
//3.解析request请求,返回的是List集合,List集合中存放的是FileItem对象
List<FileItem> list = servletFileUpload.parseRequest(request);
//定义一个List集合,用于保存复选框口味的数据
List<String> tasteList = new ArrayList<String>();
//4.遍历集合,获得每个FileItem,判断是表单项还是文件上传项
String url = null;
for (FileItem fileItem : list) {
//判断是表单项还是文件上传项
if(fileItem.isFormField()) {
//普通表单项
//接受表单项参数的值
String name = fileItem.getFieldName();//获得表单项的name属性的值
String value = fileItem.getString("UTF-8");//获得表单项的值
//接受复选框的数据
if("taste".equals(name)) {
String tasteValue = fileItem.getString("UTF-8");
//接收到一个值,将这个值存入到tasteList集合中
tasteList.add(tasteValue);
tasteValue = tasteList.toString().substring(1, tasteList.toString().length()-1);
//将口味的数据存入到Map集合中
map.put(name, tasteValue);
}else {
//将普通数据存入到Map集合中
map.put(name, value);
}
}else {
//文件上传项
//文件上传功能
//获得文件上传的名称
String fileName = fileItem.getName();
if(fileName!=null && !"".equals(fileName)) {
//通过工具类获得唯一文件名
String uuidFileName = UploadUtils.getUUIDFileName(fileName);
//获得文件上传的数据
InputStream is = fileItem.getInputStream();
//获得文件上传的路径
String path = this.getServletContext().getRealPath("/upload");
url = path + "\\" + uuidFileName;
//将输入流对接到输出流
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();
}
}
}
//获得FoodDaoImpl对象
FoodDaoImpl foodDaoImpl = new FoodDaoImpl();
List<Food> foodList = foodDaoImpl.getAllFood();
for (Food f : foodList) {
if(f.getId()==Integer.parseInt(map.get("id"))) {
request.setAttribute("msg", "菜品id已经存在!");
request.getRequestDispatcher("/addFood.jsp").forward(request, response);
return;
}
}
//封装数据到Food中
Food food = new Food();
food.setId(Integer.parseInt(map.get("id")));
food.setFoodName(map.get("foodName"));
food.setTaste(map.get("taste"));
food.setPrice(Double.parseDouble(map.get("price")));
food.setFoodImage(url);
food.setDescription(map.get("description"));
//将菜品信息存入到List集合中
foodDaoImpl.addFood(food);
for (Food fd : foodList) {
System.out.println(fd);
}
this.getServletContext().setAttribute("list", foodList);
//response.sendRedirect(request.getContextPath() + "/showFoodList.jsp");
request.getRequestDispatcher("/showFoodList.jsp").forward(request, response);
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
3.package com.imooc.servlet;
import java.io.IOException;
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.imooc.domain.Food;
/**
* Servlet implementation class SelectServlet
*/
@WebServlet("/SelectServlet")
public class SelectServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
String foodName = request.getParameter("foodName");
if(foodName.equals("")||foodName==null) {
this.getServletContext().getAttribute("list");
request.getRequestDispatcher("/showFoodList.jsp").forward(request, response);
}else {
List<Food> fd = (List<Food>) this.getServletContext().getAttribute("list");
for (Food food : fd) {
System.out.println(food.getFoodName());
System.out.println(foodName);
if(foodName.equals(food.getFoodName())) {
this.getServletContext().setAttribute("list", food);
request.getRequestDispatcher("/showFoodList.jsp").forward(request, response);
return;
}
}
}
System.out.println(foodName);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
4.
<%@page import="java.util.*"%>
<%@page import="com.imooc.domain.Food"%>
<%@page import="org.apache.jasper.tagplugins.jstl.core.ForEach"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html>
<html>
<head>
<base href="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>菜品信息展示</title>
<style type="text/css">
</style>
</head>
<body>
<center>
<h1>菜品查询</h1>
<table border="1px" cellspacing="0px" cellpadding="0px" width="800px">
<thead>
<tr>
<th>菜品ID</th>
<th>菜名</th>
<th>口味</th>
<th>菜品图片</th>
<th>价格</th>
<th>菜品描述</th>
</tr>
</thead>
<tbody>
<%
List<Food> foodList = (List<Food>)application.getAttribute("list");
System.out.println(foodList);
for(Food fd : foodList){
Object id = fd.getId();
Object foodName = fd.getFoodName();
Object taste = fd.getTaste();
int idx = fd.getFoodImage().lastIndexOf("\\");
String filePath = fd.getFoodImage().substring(idx+1);
Object price = fd.getPrice();
Object description = fd.getDescription();
%>
<tr>
<td><%=id %></td>
<td><%=foodName %></td>
<td><%=taste %></td>
<td><img src="/menu_system/upload/<%=filePath%>"/></td>
<td><%=price %></td>
<td><%=description %></td>
</tr>
<%
}
%>
</tbody>
</table>
</center>
</body>
</html>
老师,上面分别是1.FoodDaoImpl 2.FoodAddServlet 3.SelectServlet 4.showFoodList.jsp,现在根据菜名查询如果我不输入任何值的话能查出全部,但如果我输入某一个词就显示500错误了
正在回答 回答被采纳积分+1
对于报错,我们首先要学会查看报错信息。以便进一步定位问题,寻找解决方案。
java.lang.ClassCastException: com.imooc.domain.Food cannot be cast to java.util.List
试着翻译一下大体是什么意思。类型转换异常,Food类型不能被强转成List类型。
也就是说。我们从application.getAttribute("list") 取出的list并非一个List类型的对象,而是Food类型的对象。
于是我们去检查自己的代码,发现我们放进去的就是Food对象,不是List对象:

如果还有疑问,可以继续提问。
祝学习愉快~
同学你好。请下次贴代码的时候,也把完整的报错信息截图。
经检查,同学这里有多处空指针异常,所以浏览器报了500
1、

要避免这个空指针错误有两种思路。
第一种思路“||”有逻辑短路的能力。也就是说,只有两者为真才为真,所以如果符号前面那个表达式已经是false了,就不会再继续去判断符号后面那个。反之,先判断完前一个条件再判断后一个。
这里同学可以利用这个短路,将foodName==null 和 foodName.equals("") 换换位置。先判断foodName为null的话,就不会调用其equals方法了。
另外一种思路,还可以将 foodName.equals("") 改为 "".equals(foodName) 因为""这个字符串一直存在,所以不会有空指针问题。
2、

在循环遍历food的list之前,需要先判断它是不是null应该这样修改:

3、第三处同理,只是在jsp页面中,如图修改为:

如果还有疑问,可以继续提问。如果解答了同学的疑问,望采纳~
祝学习愉快~
- 参与学习 人
- 提交作业 1088 份
- 解答问题 10204 个
如果你有Java语言基础,又想以后从事Java Web开发,那么本路径是你的不二选择!本路径从网页搭建开始入手,通过大量案例来学习Java Web基础。定能助你完成Java Web小白的蜕变!
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星