我正在尝试实现自动完成。xhtml 文件中的代码:
<h:form>
<p:panelGrid cellpadding="5" columns="2">
<p:outputLabel value="Login:" for="name"/>
<p:autoComplete id="name" value="#{autoBean.user}" completeMethod="#{uB.completeUser}" var="user"
itemLabel="#{user.login}" itemValue="#{user}" converter="userConverter" dropdown="true" forceSelection="true"/>
<p:commandButton actionListener="#{autoBean.aList}">
<f:ajax execute="name" render="out"/>
</p:commandButton>
<p:outputLabel id="out" value="#{autoBean.user.login}"/>
</p:panelGrid>
</h:form>
Bean中的代码:
@ManagedBean(name="aB", eager = true)
@SessionScoped
public class AutoBean implements Serializable{
private User user;
private Locale locale;
private List<User> users;
@PostConstruct
void init() {
user = new User();
DAOImpl dao = new DAOImpl();
users = dao.getAllUsers();
locale = new Locale("ru");
}
public List<User> completeUser(String query) {
List<User> filteredUsers = new ArrayList<>();
for (User user : users) {
if (user.getLogin().toLowerCase().startsWith(query)) {
filteredUsers.add(user);
}
}
// Сортировка пользователей в автодополнении
filteredUsers.sort(new Comparator<User>() {
public int compare(User s1, User s2) {
return s1.getLogin().compareToIgnoreCase(s2.getLogin());
}
});
// Getters & Setters
}
类UserConverter
:
@FacesConverter("userConverter")
public class UserConverter implements Converter {
public Object getAsObject(FacesContext fc, UIComponent uic, String value) {
if(value != null && value.trim().length() > 0) {
try {
AutoBean autoBean = (AutoBean) fc.getExternalContext().getApplicationMap().get("aB"); // NullPointerException
return autoBean.getUsers().get(Integer.parseInt(value));
} catch(NumberFormatException e) {
throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Conversion Error", "Not a valid theme."));
}
}
else {
return null;
}
}
@Override
public String getAsString(FacesContext arg0, UIComponent arg1, Object obj) {
if(obj != null) {
return String.valueOf(((User) obj).getLogin());
}
else {
return null;
}
}
}
我NullPointerException
上线
AutoBean autoBean = (AutoBean) fc.getExternalContext().getApplicationMap().get("aB");
在调试器中 - autoBean = null
. 我查看了所有文档,但找不到原因。自动完成本身有效,用户列表可见,单击按钮时发生错误。
JavaDoc
ExternalContext.getApplicationMap()
说也就是说,该方法只允许访问具有生命周期的组件
@ApplicationScoped
在您的情况下,您应该使用其中之一
ExternalContext.getSessionMap()
,因为 该组件被标记为@SessionScoped
,或更通用FacesContext.getELContext().getELResolver()
: