所以这就是事情。我尝试使用jsp在网站的主页面上显示一些消息列表。但是当tomcat服务器启动时,我只能看到这个错误" HTTP状态500 - java.lang.NullPointerException"指向" for(消息消息:messageList)"
这是servlet的代码:
public class MainPageServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
MessageManager manager = new MessageManager();
List<Message> messageList = manager.getMessages();
request.setAttribute("messages", messageList);
request.getRequestDispatcher("/main-page.jsp").include(request, response); } }
这是jsp的一部分:
<%
List<Message> messageList = (List<Message>) request.getAttribute("messages");
for (Message message : messageList) {
%>
<div class="row" style="margin-top: 15px">
<div class="col-md-4 col-md-offset-4">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">
<%= message.getLogin()%>
</h3>
</div>
<div class="panel-body">
<%= message.getMessage() %>
</div>
<div class="panel-footer">
Posted at: <%= message.getDate() %>
</div>
</div>
</div>
</div>
<%
}
%>
我已经测试了获取messageList的结果,并且它已经100%正常。那么bug在哪里? Thnx提前帮忙!
答案 0 :(得分:0)
在您的scriptlet中,首先检查您的消息是否为空。喜欢,
if (request.getAttribute("messages") != null){
List<Message> messageList = (List<Message>) request.getAttribute("messages");
for (Message message : messageList) {
%>
<div class="row" style="margin-top: 15px">
<div class="col-md-4 col-md-offset-4">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">
<%= message.getLogin()%>
</h3>
</div>
<div class="panel-body">
<%= message.getMessage() %>
</div>
<div class="panel-footer">
Posted at: <%= message.getDate() %>
</div>
</div>
</div>
</div>
<%
}
}
%>
所以你可能不会遇到空指针异常。如果您没有通过请求获取任何数据,请使用会话在页面上发送值。试试让我知道..
答案 1 :(得分:0)
List<Message> messageList = (List<Message>) request.getAttribute("messages");
这里你没有输入演员......
<%MainPageServlet messageList = (MainPageServlet) request.getAttribute("messages"); %>
试试这个,它可以帮到你
注意:未经测试