SearchGoodsByIdServlet.java:45 下一句 空指针异常

SearchGoodsByIdServlet.java:45 下一句 空指针异常

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
严重: 在路径为[/Gim]的上下文中,servlet[com.imooc.gim.SearchGoodsByIdServlet]的Servlet.service()引发异常
java.lang.NullPointerException
    at com.imooc.gim.SearchGoodsByIdServlet.doPost(SearchGoodsByIdServlet.java:45)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:681)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
    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:196)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:698)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:364)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:624)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:831)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1650)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
    at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)
     
     
package com.imooc.gim;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * Servlet implementation class SearchGoodsByIdServlet
 */
@WebServlet("/sg")
public class SearchGoodsByIdServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
        
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SearchGoodsByIdServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(request, response);
}
/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  String id = request.getParameter("id");
  Integer goodsId = Integer.parseInt(id);
  ServletContext context=request.getServletContext();
  context.getAttribute("goods");
  List goodsList=(List)context.getAttribute("goods");
  for(int i=0; i<goodsList.size(); i++) {
  if( ((Goods) goodsList.get(i)).getGoodsId() == goodsId ) {  //这一句有问题?
  System.out.println("商品id已查询到");
  break;
   }else {
   System.out.println("商品id不存在");
   break;
   }
    
  }
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> 
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
  
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>商品列表</title>
    <link href="css/bootstrap.css" type="text/css" rel="stylesheet">
    </link>
    <script type="text/javascript" src="js/jquery-1.11.1.min.js"></script>
    <script type="text/javascript" src="js/bootstrap.js"></script>
    <style type="text/css">
    .pagination {
        margin: 0px
    }
    .pagination>li>a,
    .pagination>li>span {
        margin: 0 5px;
        border: 1px solid #dddddd;
    }
    .glyphicon {
        margin-right: 3px;
    }
    .form-control[readonly] {
        cursor: pointer;
        background-color: white;
    }
    #dlgPhoto .modal-body {
        text-align: center;
    }
    .preview {
        max-width: 500px;
    }
    </style>
    <script>
        $(function () {
             
            $("#btnAdd").click(function () {
                $('#dlgForm').modal()
            });
        })
    </script>
</head>
<body>
    <div class="container">
        <div class="row">
            <h1 style="text-align: center">IMOOC商品信息表</h1>
            <div class="panel panel-default">
                <div class="clearfix panel-heading ">
                    <div>
                        <label class="form-inline">
                            <div class="form-group" style="width: 850px;">
                                <button class="btn btn-primary" id="btnAdd">新增
                                </button>
                            </div>
                            <div class="form-group pull-right">
                            <form action="/Gim/sg" method="post">
                                <input type="text" class="form-control" id="searchById" name="id" placeholder="根据商品id进行查询">
                                <button type="submit" class="btn btn-primary">查询</button>
                                </form>
                            </div>
                        </label>
                    </div>
                    <table class="table table-bordered table-hover">
                        <thead>
                            <tr>
                                <th>序号</th>
                                <th>商品编号</th>
                                <th>商品名称</th>
                                <th>商品类别</th>
                                <th>价格</th>
                                <th>备注</th>
                                <th>&nbsp;</th>
                            </tr>
                            <c:forEach items="${applicationScope.goods}" var ="good" varStatus="idx">
                            <tr>
                                <th>${idx.index+1}</th>
                                <th>${good.goodsId}</th>
                                <th>${good.goodsName}</th>
                                <th>${good.goodsType}</th>
                                <th>¥<fmt:formatNumber value = "${good.price}" pattern="0,000.00"></fmt:formatNumber></th>
                                <th>${good.goodsRemark}</th>
                                <th>&nbsp;</th>
                            </tr>
                            </c:forEach>
                        </thead>
                    </table>
                </div>
            </div>
        </div>
        <!-- 表单 -->
        <div class="modal fade" tabindex="-1" role="dialog" id="dlgForm">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span>
                        </button>
                        <h4 class="modal-title">新增商品</h4>
                    </div>
                    <div class="modal-body">
                        <form action="/Gim/create" method="post">
                            <div class="form-group">
                                <label>商品编号</label>
                                <input type="text" name="goodsId" class="form-control" id="empno" placeholder="请输入商品编号">
                            </div>
                            <div class="form-group">
                                <label>商品名称</label>
                                <input type="text" name="goodsName" class="form-control" id="ename" placeholder="请输入商品名称">
                            </div>
                            <div class="form-group">
                                <label>商品类别</label>
                                <select id="gname" name="goodsType" class="form-control">
                                    <option selected="selected">服装</option>
                                    <option value="家用">家用电器</option>
                                    <option value="生活">生活用品</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <label>价格</label>
                                <input type="text" name="price" class="form-control" id="sal" placeholder="请输入价格">
                            </div>
                            <div class="form-group">
                                <label>备注</label>
                                <input type="text" name="description" class="form-control" id="sal" placeholder="请输入备注">
                            </div>
                            <div class="form-group" style="text-align: center;">
                                <button type="submit" class="btn btn-primary">保存</button>
                            </div>
                        </form>
                    </div>
                </div><!-- /.modal-content -->
            </div><!-- /.modal-dialog -->
        </div><!-- /.modal -->
</body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package com.imooc.gim;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * Servlet implementation class GoodsAddServlet
 */
@WebServlet("/gl")
public class GoodsListServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
    /**
     * Default constructor. 
     */
    public GoodsListServlet() {
        // TODO Auto-generated constructor stgaub
    }
/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       doPost(request, response);
}
/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    request.setCharacterEncoding("utf-8");
    ServletContext context=request.getServletContext();
    if(context.getAttribute("goods")==null) {   
         
    List<Goods> goodsList=new ArrayList<>();
    goodsList.add(new Goods(1001,"格力空调","家用电器",3000.00f,"铂金品质"));
    goodsList.add(new Goods(1002,"LV","服装",18888.00f,"生活一场旅行"));
    context.setAttribute("goods", goodsList);
     
    }    
     
     
    request.getRequestDispatcher("/goods.jsp").forward(request, response);
     
   }
     
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package com.imooc.gim;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * Servlet implementation class GoodsAddServlet
 */
@WebServlet("/create")
public class GoodsAddServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
        
    /**
     * @see HttpServlet#HttpServlet()
     */
    public GoodsAddServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
String goodsId=request.getParameter("goodsId");
    String goodsName=request.getParameter("goodsName");
    String goodsType=request.getParameter("goodsType");
    String price=request.getParameter("price");
    String goodsRemark=request.getParameter("description");
    System.out.println(goodsId);
    Goods good = new Goods(Integer.parseInt(goodsId),goodsName,goodsType,Float.parseFloat(price),goodsRemark);
    ServletContext context=request.getServletContext();
    context.getAttribute("goods");
    List goodsList=(List)context.getAttribute("goods");
goodsList.add(good);
    context.setAttribute("goods", goodsList);
    request.getRequestDispatcher("/gl").forward(request, response);
}
}
package com.imooc.gim;
public class Goods {
 private Integer goodsId;
 private String goodsName;
 private String goodsType;
 private float price;
 private String goodsRemark;
public Goods(Integer goodsId, String goodsName, String goodsType, float price, String goodsRemark) {
super();
this.goodsId = goodsId;
this.goodsName = goodsName;
this.goodsType = goodsType;
this.price = price;
this.goodsRemark = goodsRemark;
}
public Integer getGoodsId() {
return goodsId;
}
public void setGoodsId(Integer goodsId) {
this.goodsId = goodsId;
}
public String getGoodsName() {
return goodsName;
}
public void setGoodsName(String goodsName) {
this.goodsName = goodsName;
}
public String getgoodsType() {
return goodsType;
}
public void setgoodsType(String goodsType) {
this.goodsType = goodsType;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public String getGoodsRemark() {
return goodsRemark;
}
public void setGoodsRemark(String goodsRemark) {
this.goodsRemark = goodsRemark;
}
@Override
public String toString() {
return "Goods [goodsId=" + goodsId + ", goodsName=" + goodsName + ", goodsType=" + goodsType
", price=" + price + ", goodsRemark=" + goodsRemark + "]";
}
  
}


正在回答

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

1回答

同学你好,测试过同学代码之后,并未复现空指针异常。但同学的代码中存在逻辑问题:

当判断用户输入的ID在集合中是否有对应商品的时候,应当是将集合完整遍历结束之后才能确定没有找到。而同学的代码,循环只会进行一次,无论是否找到都会被break结束循环。

修改后的代码如下图所示:

https://img1.sycdn.imooc.com//climg/61ac4e80097b263d10230726.jpg

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//定义标记变量,如果没有找到flag的值为true,找到则更改为false
boolean flag = true;
//遍历集合
for (int i = 0; i < goodsList.size(); i++) {
    //获取集合中i下标的Goods对象
    Goods goods = (Goods)goodsList.get(i);
    //获取对象的id值
    Integer gid = goods.getGoodsId();
    //如果id和用户输入的id相同,则找到
    //注意:Integer类型数据对比需要使用equals而不是==
    if(gid.equals(goodsId)) {
        System.out.println("商品id已查询到");
        //将标记变量修改为false
        flag = false;
    }
}
//循环结束后,查看标记变量,判断是否
if(flag) System.out.println("商品id不存在");

如果同学依然出现空指针异常,建议将操作步骤和错误截图一并提供。

祝学习愉快~


  • 晓舟 提问者 #1
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    package com.imooc.gim;
    import java.io.IOException;
    import java.util.List;
    import javax.servlet.ServletContext;
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    /**
     * Servlet implementation class SearchGoodsByIdServlet
     */
    @WebServlet("/sg")
    public class SearchGoodsByIdServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
            
        /**
         * @see HttpServlet#HttpServlet()
         */
        public SearchGoodsByIdServlet() {
            super();
            // TODO Auto-generated constructor stub
        }
    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    doPost(request, response);
    }
    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      String id = request.getParameter("id");
      Integer goodsId = Integer.parseInt(id);
      ServletContext context=request.getServletContext();
      context.getAttribute("goods");
      List goodsList=(List)context.getAttribute("goods");
      for(int i=0; i<goodsList.size(); i++) {
      Integer good = ((Goods) goodsList.get(i)).getGoodsId();
      if(good.equals(goodsId) ) {
      System.out.println("商品id已查询到");
      break;     
      }
       }
    }
    }
     
    //修改成这样后,如果输入的商品id正好合list中匹配控制台应该输出 商品已查询到,为什么还是报空指针异常呢?
    严重: 在路径为[/Gim]的上下文中,servlet[com.imooc.gim.SearchGoodsByIdServlet]的Servlet.service()引发异常
    java.lang.NullPointerException
        at com.imooc.gim.SearchGoodsByIdServlet.doPost(SearchGoodsByIdServlet.java:45)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:681)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
        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:196)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
        at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:698)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:364)
        at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:624)
        at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
        at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:831)
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1650)
        at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
        at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
        at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
        at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
        at java.lang.Thread.run(Unknown Source)
    2021-12-05 13:53:22
  • 好帮手慕小蓝 回复 提问者 晓舟 #2

        同学你好,老师这里使用同学的代码进行测试,并没有出现空指针异常。

        老师的测试方式是:

    1. 通过url:gl访问并展示页面;

    2. 在页面中输入1002进行查询;

    3. 在SearchGoodsByIdServlet接收数据并进行查询。

        以上步骤并不会出现空指针异常。

        如果同学在测试的时候,只是刷新页面,而不是通过地址栏重新访问gl的话,是会出现空指针的,因为List集合的数据时通过访问Servlet存储的,如果直接刷新页面就没有存储的过程,会在获取List的时候出现空指针。

        如果以上都不是同学出现空指针的情况,建议同学描述一下具体的操作过程。

        祝学习愉快~

    2021-12-05 14:34:52
问题已解决,确定采纳
还有疑问,暂不采纳

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

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

0 星
请稍等 ...
微信客服

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

帮助反馈 APP下载

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

公众号

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

在线咨询

领取优惠

免费试听

领取大纲

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