Я создал веб-приложение на Java, используя JSF 2.
Когда пользователь входит в мое приложение, я сохраняю его идентификатор в сеансе, поэтому:
FacesContext context = FacesContext.getCurrentInstance();
context.getExternalContext().getSessionMap().put("userid", myBean.getUserId());
Затем я создал свой фильтр:
public class PageFilter implements Filter {
private FilterConfig filterconfig;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
this.filterconfig = filterconfig;
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httprequest =(HttpServletRequest) request;
HttpServletResponse httpresponse =(HttpServletResponse) response;
HttpSession session = ((HttpServletRequest) request).getSession();
String userid = (String) session.getAttribute("userid");
String pageRequested = httprequest.getRequestURI();
try {
if( userid != null && pageRequested.contains("index.xhtml") ) {
System.out.printf("User authenticated with " + httprequest.getRemoteUser() + " username conected.");
httprequest.getRequestDispatcher("/service/home.xhtml").forward(request, response);
} else {
chain.doFilter(request, response);
}
}catch(IOException | ServletException e){
//do something
}
}
@Override
public void destroy() {
System.out.print("Existing from loginFilter");
}
}
Моя задача - управлять кнопкой обновления браузера, поэтому, если пользователь уже вошел в систему, он перенаправляется на /service/home.xhtml. Кроме того, URL-адрес в моем веб-приложении всегда:
localhost:8080/myapplication
Таким образом, если пользователь просматривает сайт среди всех страниц, URL всегда будет таким (действие скрыто).
Проблема заключается в том, что если пользователь щелкает URL-адрес в браузере, запрос выполняется для index.xhtml, а моя сессия имеет значение null (я не могу получить идентификатор пользователя с помощью session.getAttribute ("userid");).
Где моя вина?
Index.xhtml определен как список файлов приветствия в моем файле web.xml:
<welcome-file-list>
<welcome-file>index.xhtml</welcome-file>
</welcome-file-list>
Спасибо.