空指针异常,求解决
来源:5-2 作业题
爱动脑筋的小伙伴
2019-03-07 17:08:21
package com.imooc.domain;
public class Food {
private String ID;
private String name;
private String taste;
private String picAddress;
private String price;
private String description;
public Food() {
super();
}
public Food(String iD, String name, String taste, String picAddress, String price, String description) {
super();
this.ID = iD;
this.name = name;
this.taste = taste;
this.picAddress = picAddress;
this.price = price;
this.description = description;
}
public String getID() {
return ID;
}
public void setID(String iD) {
ID = iD;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTaste() {
return taste;
}
public void setTaste(String taste) {
this.taste = taste;
}
public String getPicAddress() {
return picAddress;
}
public void setPicAddress(String picAddress) {
this.picAddress = picAddress;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Override
public String toString() {
return "菜品ID:" + ID + ", 菜名:" + name + ", 口味:" + taste + ", 价格:"
+ price + ", 描述:" + description;
}
}Food内容
package com.imooc.util;
import java.util.ArrayList;
import java.util.List;
import com.imooc.domain.Food;
public class FoodDaoImpl {
//存放菜品信息的List
private static final List<Food> list = new ArrayList<Food>();
//添加菜品
public void addFood(Food food) {
this.list.add(food);
}
//查询所有菜品信息
public List<Food> getAllFood(){
return list;
}
//根据菜品名称查询菜品信息
public Food getFoodByName(String foodName) {
return null;
}
//根据菜品id查询菜品信息
public Food getFoodById(String id) {
return null;
}
//菜品修改
public void updateFood(Food newFood) {
}
//根据菜品ID进行删除
public void deleteFoodById(String id) {
}
}FoodDaoImpl
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> <display-name>Homework5-2</display-name> <welcome-file-list> <welcome-file>server.jsp</welcome-file> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <servlet> <description></description> <display-name>initServlet</display-name> <servlet-name>initServlet</servlet-name> <servlet-class>com.imooc.servlet.initServlet</servlet-class> <load-on-startup>2</load-on-startup> </servlet> <servlet-mapping> <servlet-name>initServlet</servlet-name> <url-pattern>/initServlet</url-pattern> </servlet-mapping> </web-app>
web-xml
package com.imooc.servlet;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import com.imooc.util.FoodDaoImpl;
/**
* Servlet implementation class initServlet
*/
public class initServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public initServlet() {
super();
// TODO Auto-generated constructor stub
}
public void init() throws ServletException {
FoodDaoImpl foodDaoImpl=new FoodDaoImpl();
this.getServletContext().setAttribute("FoodDaoImpl", foodDaoImpl);
}
}initservlet
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.util.FoodDaoImpl;
import com.imooc.util.UploadUtils;
/**
* Servlet implementation class FoodAddServlet
*/
@WebServlet("/FoodAddServlet")
public class FoodAddServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public FoodAddServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(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");// 获得表单项的值
// System.out.println(name+" "+value);
// 接收复选框的数据
// if("taste".equals(name)){
// String tasteValue = fileItem.getString("UTF-8");
// // 接收到一个值,将这个值存入到hobbyList集合中
// tasteList.add(tasteValue);
// tasteValue = tasteList.toString().substring(1, tasteList.toString().length()-1); // xxx,yyy
// System.out.println(name+" "+tasteValue);
// // 将爱好的数据存入到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();
}
}
}
// System.out.println(map);
// 获得FoodDaoImpl对象:
FoodDaoImpl foodDaoImpl=(FoodDaoImpl)this.getServletContext().getAttribute("FoodDaoImp");
List<Food> foodList = foodDaoImpl.getAllFood();
// 校验菜品ID:
for(Food f :foodList){
if(f.getID().equals(map.get("ID"))){
request.setAttribute("msg", "菜品已经存在!");
request.getRequestDispatcher("/addFood.jsp").forward(request, response);
return ;
}
}
// 封装数据到User当中:
Food food = new Food();
food.setID(map.get("ID"));
food.setName(map.get("foodName"));
food.setPicAddress(url);
food.setPrice(map.get("price"));
food.setDescription(map.get("description"));
// 将注册用户的信息存入到List集合中:
foodDaoImpl.addFood(food);
// for (User u : userList) {
// System.out.println(u);
// }
this.getServletContext().setAttribute("FoodDaoImp", foodDaoImpl);
// 注册成功,跳转到菜品查询:
// request.getSession().setAttribute("username", user.getUsername());
response.sendRedirect(request.getContextPath()+"/showFoodList.jsp");
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}addFoodServlet
3回答
同学存的时候是存的FoodDaoImpl ,取的时候,写的是FoodDaoImp


所以取不到。
空指针异常一定是有值为null的对象去掉方法了,同学就要检查一下,为什么取出来的这个对象是null就可以了。
2、使用InitServlet就不要使用FoodDaoImpl了,都是存数据,选择其中一个使用就可以了,要么存到FoodDaoImpl中的db中去,要么在InitServlet中在域中初始化一个集合存储,不要两个同时使用哟。FoodDaoImpl的对象直接new就行,不用在InitServlet中初始化
如果我的回答解决了你的疑惑,请采纳!祝学习愉快!
爱动脑筋的小伙伴
提问者
2019-03-07
空指针异常发生在
FoodDaoImpl foodDaoImpl=(FoodDaoImpl)this.getServletContext().getAttribute("FoodDaoImp");
List<Food> foodList = foodDaoImpl.getAllFood();
爱动脑筋的小伙伴
提问者
2019-03-07
我是想通过一个initservlet类,把foodDaoimpl的一个对象存在servletcontext中,随时调出来用,但是调出来的时候就空指针异常了
相似问题