Utworzenie nowego realm'a
Dodanie użytkowników i ról
Struktura mojej aplikacji demo
Plik sun-web.xml
Plik web.xml
Strona logowania
Managed bean z funkcją odpowiedzialną za autentykację
import javax.faces.application.FacesMessage;; import javax.faces.bean.ManagedBean; import javax.faces.bean.RequestScoped; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; @ManagedBean @RequestScoped public class LoginBean { private String inputLogin; private String inputPassword; public String loginAction(){ FacesContext ctx = null; ExternalContext ectx = null; HttpServletRequest request = null; FacesMessage msg = null; String action = null; try { ctx = FacesContext.getCurrentInstance(); ectx = ctx.getExternalContext(); request = (HttpServletRequest) ectx.getRequest(); request.login(inputLogin, inputPassword); action = "/protected/welcome.xhtml"; } catch (ServletException ex) { ctx = FacesContext.getCurrentInstance(); msg = new FacesMessage(ex.getMessage()); msg.setSeverity(FacesMessage.SEVERITY_ERROR); ctx.addMessage(null, msg); } return action; } // getters and setters }
Jak widać nowością jest funkcja login() wywoływana na obiekcie HttpServletRequest. W przypadku niepoprawnego logowania otrzymamy w wyjątek, który można obsłużyć dowolnym faces'owym komunikatem.
Analogicznie, możemy wywołać funkcję logout(), przy czym należy pamiętać, że wylogowanie musi się odbywać z redirect'em
@ManagedBean @RequestScoped public class WelcomeBean { public String logoutAction(){ FacesContext ctx = null; ExternalContext ectx = null; HttpServletRequest request = null; String action = null; try { ctx = FacesContext.getCurrentInstance(); ectx = ctx.getExternalContext(); request = (HttpServletRequest)ectx.getRequest(); request.logout(); action = "/faces/index.xhtml?faces-redirect=true"; } catch (ServletException ex) { ex.printStackTrace(); } return action; } }
Pobierz projekt (NetBeans 6.9.1)
Dzięki za info :)
OdpowiedzUsuńBędę musiał przerobić swoją aplikację