根据菜名查询不出

根据菜名查询不出

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

登陆购买课程后可参与讨论,去登陆

2回答
芝芝兰兰 2019-03-25 13:53:32

对于报错,我们首先要学会查看报错信息。以便进一步定位问题,寻找解决方案。

java.lang.ClassCastException: com.imooc.domain.Food cannot be cast to java.util.List

试着翻译一下大体是什么意思。类型转换异常,Food类型不能被强转成List类型。

也就是说。我们从application.getAttribute("list") 取出的list并非一个List类型的对象,而是Food类型的对象。

于是我们去检查自己的代码,发现我们放进去的就是Food对象,不是List对象:

http://img1.sycdn.imooc.com//climg/5c986b2d0001a3b709580290.jpg

如果还有疑问,可以继续提问。

祝学习愉快~


  • 提问者 泽Changer #1
    但想根据菜名查询的话就只是在页面显示foodList集合中的某一条啊,那我怎么在不改变showFoodList.jsp的代码的前提下在SelectServlet中判断我不输入关键词时就查询全部,而当我输入比如回锅肉时就显示回锅肉的菜品呢?
    2019-03-25 15:12:15
  • 芝芝兰兰 回复 提问者 泽Changer #2
    建议将SelectServlet和FoodDaoImpl一同调整,在提交到SelectServlet中时,可以拼接一个flag来判断是查找全部还是按名称查找。查找全部还是调用getAllFood() 。按名称查找去调用FoodDaoImpl中的getFoodByName方法。并且将这个方法的返回值改为List<Food>,返回一个只有一个Food元素的List,当找不到,List的size为0。
    2019-03-25 16:23:52
  • 提问者 泽Changer 回复 芝芝兰兰 #3
    老师,就通过文字我实在搞不懂,能不能直接发代码以供参考呢?
    2019-03-27 14:52:39
芝芝兰兰 2019-03-19 17:52:56

同学你好。请下次贴代码的时候,也把完整的报错信息截图。

经检查,同学这里有多处空指针异常,所以浏览器报了500

1、

http://img1.sycdn.imooc.com//climg/5c90b1670001dde107750107.jpg

要避免这个空指针错误有两种思路。

第一种思路“||”有逻辑短路的能力。也就是说,只有两者为真才为真,所以如果符号前面那个表达式已经是false了,就不会再继续去判断符号后面那个。反之,先判断完前一个条件再判断后一个。

这里同学可以利用这个短路,将foodName==null 和 foodName.equals("") 换换位置。先判断foodName为null的话,就不会调用其equals方法了。

另外一种思路,还可以将 foodName.equals("") 改为 "".equals(foodName) 因为""这个字符串一直存在,所以不会有空指针问题。


2、

http://img1.sycdn.imooc.com//climg/5c90b90900012cfc09400130.jpg

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

http://img1.sycdn.imooc.com//climg/5c90b96400011ab911920572.jpg


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

http://img1.sycdn.imooc.com//climg/5c90b9f4000125f707820196.jpg


如果还有疑问,可以继续提问。如果解答了同学的疑问,望采纳~

祝学习愉快~


  • 提问者 泽Changer #1
    感觉老师有点答非所问,我不是说有foodName为空时有问题,而是foodName有值时才有问题。就是我在菜品查询那个页面不输入任何关键词时能查出全部菜品,但当我输入某一个明明存在于list中的菜品时却显示500错误。即使我按老师所说的改了,问题还是一样,错误信息提示问题出在List<Food> foodList = (List<Food>)application.getAttribute("list");这句,具体错误为java.lang.ClassCastException: com.imooc.domain.Food cannot be cast to java.util.List。
    2019-03-25 11:14:13
  • 芝芝兰兰 回复 提问者 泽Changer #2
    同学你好,为了格式,我将重新追加答复在回答中,非常抱歉定位错了同学的问题。也请下次同学帮帮我,把报错的位置和提示信息都贴出来,就像你这次的回复一样就很好~
    2019-03-25 13:53:05
问题已解决,确定采纳
还有疑问,暂不采纳

恭喜解决一个难题,获得1积分~

来为老师/同学的回答评分吧

0 星
从网页搭建入门Java Web2018版
  • 参与学习           人
  • 提交作业       1088    份
  • 解答问题       10204    个

如果你有Java语言基础,又想以后从事Java Web开发,那么本路径是你的不二选择!本路径从网页搭建开始入手,通过大量案例来学习Java Web基础。定能助你完成Java Web小白的蜕变!

了解课程
请稍等 ...
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号

在线咨询

领取优惠

免费试听

领取大纲

扫描二维码,添加
你的专属老师