Пытаюсь реализовать autocomplete. Код в 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() сообщает, что
Return a mutable Map representing the application scope attributes for the current application
Т.е., метод даёт доступ только к компонентам с жизненным циклом @ApplicationScoped
В вашем случае следует использовать либо ExternalContext.getSessionMap(), т.к. компонент помечен как @SessionScoped, либо более универсальный FacesContext.getELContext().getELResolver():
fc.getELContext().getELResolver().getValue(fc.getELContext(), null,"aB")
Современные инструменты для криптотрейдинга: как технологии помогают принимать решения
Апостиль в Лос-Анджелесе без лишних нервов и бумажной волокиты
Основные этапы разработки сайта для стоматологической клиники
Продвижение своими сайтами как стратегия роста и независимости