老师,再看看为什么会出现空指针?我知道问题是空指针,我需要了解如何解决?
来源:5-2 作业题
慕容3475906
2019-02-15 17:16:10
SERVLET文件:
package com.imooc.servlet;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
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.MenuItem;
import com.imooc.utils.UploadUtils;
/**
* 菜品添加的Servlet
*/
public class FoodAddServlet extends HttpServlet {
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);
// 4.遍历集合,获得每个FileItem,判断是表单项还是文件上传项
String url = null;
for (FileItem fileItem : list) {
// 判断是表单项还是文件上传项
if(fileItem.isFormField()){
// 普通表单项:
// 接收表单项参数的值:
String name = fileItem.getFieldName(); // 获得表单项的name属性的值
String value = fileItem.getString("UTF-8");// 获得表单项的值
// 将数据存入到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();
}
}
}
// 获得ServletContext对象:
List<MenuItem> MenuList = (List<MenuItem>) this.getServletContext().getAttribute("list");
// 校验菜品是否重复
for(MenuItem u :MenuList){
if(u.getId().equals(map.get("id"))){
request.setAttribute("msg", "菜品已经存在!");
request.getRequestDispatcher("/addFood.jsp").forward(request, response);
return;
}
}
// 封装数据到MenuItem当中:
MenuItem menuitem = new MenuItem();
menuitem.setId(map.get("id"));
menuitem.setFoodName(map.get("foodName"));
menuitem.setTaste(map.get("taste"));
menuitem.setPrice(map.get("price"));
menuitem.setDescription(map.get("description"));
menuitem.setFoodImage(url);
MenuList.add(menuitem);
for (MenuItem u : MenuList) {
System.out.println(u);
}
this.getServletContext().setAttribute("list", MenuList);
// 提交成功,跳转到菜单显示页面:
request.getSession().setAttribute("menuitem", menuitem);
response.sendRedirect(request.getContextPath()+"/showFoodList.jsp");
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
JSP文件:
<%@page import="com.imooc.domain.MenuItem"%>
<%@page import="java.util.*"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<base href="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>菜品信息展示</title>
<style type="text/css">
</style>
</head>
<body>
<%
List<Map<String,String>> foodlist = (List<Map<String,String>>)request.getAttribute("list");
for(Map<String,String>map : foodlist){
String id = map.get("id");
String foodName = map.get("foodName");
String taste = map.get("taste");
String filepath = map.get("url");
String price =map.get("price");
String description = map.get("description");
%>
<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>
<tr>
<td><%= 1 %></td>
<td><%= 2 %></td>
<td><%= 3 %></td>
<td><%= 4 %>" /></td>
<td><%= 5 %></td>
<td><%= 6 %></td>
</tr>
</tbody>
</table>
</center>
<%
}
%>
</body>
</html>
7回答
你好同学,建议你创建一个InitServlet,这个类的作用是为了初始化list集合,然后将集合放在application作用域中,
public class InitServlet extends HttpServlet {
@Override
public void init() throws ServletException {
List<MenuItem> list = new ArrayList<User>();
// 将list保存到ServletContext作用域中:
this.getServletContext().setAttribute("list", list);
}
}然后在web.xml中配置该类在容器启动的时候加载。配置如下,
<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>
然后你的List<MenuItem> MenuList = (List<MenuItem>) this.getServletContext().getAttribute("list");就不会出现空指针异常了,主要就是你没有初始化list集合,是list集合为null,祝学习愉快~
慕容3475906
提问者
2019-02-15
链接在LEFT.HTML里面:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<p><a href="addFood.jsp" target="main">菜品添加</a></p>
<p><a href="selectFood.jsp" target="main">菜品查询</a></p>
<p><a href="updateFood.jsp" target="main">菜品修改</a></p>
<p><a href="deleteById.jsp" target="main">菜品删除</a></p>
</body>
</html>
慕容3475906
提问者
2019-02-15
INDEX.JSP文件:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>菜品管理系统</title>
</head>
<frameset rows="20%,*">
<frame src="./top.html"></frame>
<frameset cols="10%,*">
<frame src="./left.html"></frame>
<frame name="main"></frame>
</frameset>
</frameset>
</html>
慕容3475906
提问者
2019-02-15
老师,如果有需要提供的文件请在回答中说明,我随时提供。
慕容3475906
提问者
2019-02-15
MENUITEM类:
public class MenuItem {
private String id;
private String foodName;
private String taste;
private String foodImage;
private String price;
private String description;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getFoodName() {
return foodName;
}
public void setFoodName(String foodName) {
this.foodName = foodName;
}
public String getTaste() {
return taste;
}
public void setTaste(String taste) {
this.taste = taste;
}
public String getFoodImage() {
return foodImage;
}
public void setFoodImage(String foodImage) {
this.foodImage = foodImage;
}
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 "MenuItem [id=" + id + ", foodName=" + foodName + ", taste=" + taste + ", foodImage=" + foodImage
+ ", price=" + price + ", description=" + description + "]";
}
}
ADDFOOD.jsp文件:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<base href="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>添加菜品</title>
<style type="text/css">
</style>
</head>
<body>
<%
String msg = "";
if(request.getAttribute("msg")!=null){
msg = (String)request.getAttribute("msg");
}
%>
<h3><font color="red"><%=msg %></font></h3>
<center>
<h1>菜品添加</h1>
<form action="<%=basePath%>/FoodAddServlet" method="post" enctype="multipart/form-data">
<table border="1px" width="400px" cellspacing="0px" cellpadding="0px">
<tr>
<td>菜品 ID</td>
<td><input type="text" name="id"></td>
</tr>
<tr>
<td>菜 名</td>
<td><input type="text" name="foodName"></td>
</tr>
<tr>
<td>口 味</td>
<td>
<input type="radio" name="taste" value="香辣">香辣
<input type="radio" name="taste" value="微辣">微辣
<input type="radio" name="taste" value="麻辣">麻辣
<input type="radio" name="taste" value="不辣">不辣
</td>
</tr>
<tr>
<td>菜品图片</td>
<td><input type="file" name="foodImage"></td>
</tr>
<tr>
<td>价 格</td>
<td><input type="text" name="price"></td>
</tr>
<tr>
<td>菜品描述</td>
<td>
<textarea name="description"></textarea>
</td>
</tr>
<tr style="text-align:center;width:20px">
<td colspan="2">
<input type="submit" value="添加">
<input type="reset" value="重置">
</td>
</tr>
</table>
</form>
</center>
</body>
</html>
慕容3475906
提问者
2019-02-15
二月 15, 2019 5:09:57 下午 org.apache.catalina.core.StandardWrapperValve invoke
严重: Servlet.service() for servlet [jsp] in context with path [/orderfood] threw exception [An exception occurred processing JSP page [/showFoodList.jsp] at line [23]
20: <body>
21: <%
22: List<Map<String,String>> foodlist = (List<Map<String,String>>)request.getAttribute("list");
23: for(Map<String,String>map : foodlist){
24: String id = map.get("id");
25: String foodName = map.get("foodName");
26: String taste = map.get("taste");
Stacktrace:] with root cause
java.lang.NullPointerException
at org.apache.jsp.showFoodList_jsp._jspService(showFoodList_jsp.java:144)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:476)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:386)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:330)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:493)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:650)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:800)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:806)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1498)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
慕容3475906
提问者
2019-02-15
网页故障提示:
HTTP Status 500 – Internal Server Error
Type Exception Report
Message An exception occurred processing JSP page [/showFoodList.jsp] at line [23]
Description The server encountered an unexpected condition that prevented it from fulfilling the request.
Exception
org.apache.jasper.JasperException: An exception occurred processing JSP page [/showFoodList.jsp] at line [23]
20: <body>
21: <%
22: List<Map<String,String>> foodlist = (List<Map<String,String>>)request.getAttribute("list");
23: for(Map<String,String>map : foodlist){
24: String id = map.get("id");
25: String foodName = map.get("foodName");
26: String taste = map.get("taste");
Stacktrace:
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:617)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:514)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:386)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:330)
javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Root Cause
java.lang.NullPointerException
org.apache.jsp.showFoodList_jsp._jspService(showFoodList_jsp.java:144)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:476)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:386)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:330)
javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Note The full stack trace of the root cause is available in the server logs.
Apache Tomcat/8.5.37
相似问题