聽起來好像您正在進行身份驗證。在這種情況下,您還需要自行增加訪問限制。這通常使用servlet filter來完成。
假設你登錄爲在@RequestScoped
豆如下,
public String login() {
User user = userService.find(username, password);
FacesContext context = FacesContext.getCurrentInstance();
if (user != null) {
context.getExternalContext().getSessionMap().put("user", user);
return "dashboard.xhtml?faces-redirect=true";
} else {
context.addMessage(null, new FacesMessage("Unknown login, try again."));
return null;
}
}
然後你就可以在@WebFilter("/*")
過濾器檢查登錄的用戶,如下所示:
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws ServletException, IOException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
HttpSession session = request.getSession(false);
User user = (session != null) ? session.getAttribute("user") : null;
String loginURL = request.getContextPath() + "/login.xhtml";
boolean loginRequest = request.getRequestURI().startsWith(loginURL);
boolean resourceRequest = request.getRequestURI().startsWith(request.getContextPath() + ResourceHandler.RESOURCE_IDENTIFIER);
if (user != null || loginRequest || resourceRequest)) {
chain.doFilter(request, response);
} else {
response.sendRedirect(loginURL);
}
}
注因此當用戶登錄時,或者直接請求登錄頁面本身時,或者請求JSF資源(CSS/JS /圖像)時,這會繼續請求。
如果您使用的是容器管理的身份驗證,那麼過濾器就不必要了。另請參閱How to handle authentication/authorization with users in a database?