我正在尝试学习Java和Jsf,并且一直在从事聊天功能项目。我一直想在点击发送按钮后显示消息。 Eclipse中出现的错误是我的动作控制器addMessage方法从发送按钮出现的空指针异常。您能告诉我我的代码有什么问题吗?我已经为此进行了三天的尝试,并尝试从网上应用其他解决方案,但似乎无法修复。我非常需要此尽快,因此我将其发布在此处以寻求帮助。这是我的代码:
XHTML页面:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets">
<h:head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Chat Room</title>
</h:head>
<h:body>
<!-- Pao edited -->
<div class="title" align="center">Welcome to ACT Chat Room</div>
<!-- collective chat messages -->
<div id="chatMessageList">
<table align="center">
<tr>
<td valign="top">
<h:outputText value="#{chatPage.chatMessageList}" />
</td>
</tr>
</table>
</div>
<!-- chat message -->
<div id="chatMessage">
<h:form>
<table align="center">
<tr>
<td>Enter Message:</td>
<td><h:inputTextarea value="#{chatPage.message}" rows="3" cols="75"/></td>
<td><h:commandButton value="Send" action="#{chatPage.addMessage()}" /></td>
</tr>
</table>
</h:form>
</div>
<!-- End editing here -->
</h:body>
</html>
ChatPage类:
@ManagedBean
@SessionScoped
public class ChatPage {
private String username;
private String message;
private String creationTime;
private String id;
private List<ChatMessage> chatMessageList;
private ChatMessage chatMessage;
public ChatPage(){
}
(getters and setters)
/方法将chatPage.message放入chatMessage.message中并将其添加到chatMessageList /
public void addMessage(){
ChatMessage chatMessage = new ChatMessage();
chatMessage.setMessage(message);
this.chatMessageList.add(chatMessage);
}
}
ChatMessage类别:
public class ChatMessage {
private int id;
private String message;
private String creationTime;
(getters and setters)
}
这是我得到的错误:
java.lang.NullPointerException
actportal.view.chat.ChatPage.addMessage(ChatPage.java:65)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)
org.apache.el.parser.AstValue.invoke(AstValue.java:278)
org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:274)
将不胜感激与此有关。提前致谢!
最佳答案
您似乎没有为chatMessageList
变量分配任何内容,因此在尝试向其中添加ChatMessage
时,会出现NullPointerException
。要解决此问题,请将以下行添加到您的ChatPage
构造函数中:
chatMessageList = new ArrayList<ChatMessage>();
您将需要导入
java.util.ArrayList
。关于java - 如何从其ChatMessage类的列表中显示String消息属性?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19754925/