PhaseListener erro

16 respostas
N

Boa noite, pessoal, seguinte coloquei um exemplo de PhaseListener que peguei do exemplo do netbeans e outros que achei na net para fazer um filtro para autenticação, porem quando eu declaro ele no faces config a minha aplicação não roda ele apenas fica uma pagina em branco ao inves de redirecionar para minha pagina principal.. o home, e se eu ponho parece que o browser entra em loop infinito :/ e ja tentei varios e ainda não consegui resolver
alguem pode me ajudar?

segue o código do PhaseListener

package autenticacao;

import apresentacao.managedbean.EmpresaManagedBean;
import javax.el.ELContext;
import javax.el.ValueExpression;
import javax.faces.FacesException;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;

/**
 * <p>This <code>PhaseListener</code> will be take action before
 * the <code>Restore View</code> phase is invoked.  This allows
 * us to check to see if the user is logged in before allowing them
 * to request a secure resource.  If the user isn't logged in, then
 * the listener will move the user to the login page.</p>
 * @author rlubke
 */
public class AuthenticationPhaseListenerEmpresa implements PhaseListener {
    
    /**
     * <p>The outcome to trigger navigation to the login page.</p>
     */
    private static final String USER_LOGIN_OUTCOME = "loginEmpresa";
       
    // ---------------------------------------------- Methods from PhaseListener

    /**
     * <p>Determines if the user is authenticated.  If not, direct the
     * user to the login view, otherwise all the user to continue to the
     * requested view.</p>
     *
     * <p>Implementation Note: We do this in the <code>afterPhase</code>
     * to make use of the <code>NavigationHandler</code>.</p>
     */
    public void afterPhase(PhaseEvent event) {
        FacesContext context = event.getFacesContext();
       
        if (userExists(context)) {
            // allow processing of the requested view
            return;
        } else {            
            // send the user to the login view
            if (requestingSecureView(context)) {
                context.responseComplete();              
                context.getApplication().
                        getNavigationHandler().handleNavigation(context, 
                                                                null, 
                                                                USER_LOGIN_OUTCOME);
            }
        }
    }

    /**
     * <p>This is a no-op.</p>
     */
    public void beforePhase(PhaseEvent event) {        
    }

    /**
     * @return <code>PhaseId.RESTORE_VIEW</code>
     */
    public PhaseId getPhaseId() {
        return PhaseId.RESTORE_VIEW;
    }
    
    // --------------------------------------------------------- Private Methods       
    
    /**
     * <p>Determine if the user has been authenticated by checking the session
     * for an existing <code>Wuser</code> object.</p>
     * 
     * @param context the <code>FacesContext</code> for the current request
     * @return <code>true</code> if the user has been authenticated, otherwise
     *  <code>false</code>
     */
    private boolean userExists(FacesContext context) {
        ExternalContext extContext = context.getExternalContext();
        return (extContext.getSessionMap().containsKey(EmpresaManagedBean.USER_SESSION_KEY));
    }
    
    /**
     * <p>Determines if the requested view is one of the login pages which will
     * allow the user to access them without being authenticated.</p>
     *
     * <p>Note, this implementation most likely will not work if the 
     * <code>FacesServlet</code> is suffix mapped.</p>
     *
     * @param context the <code>FacesContext</code> for the current request
     * @return <code>true</code> if the requested view is allowed to be accessed
     *  without being authenticated, otherwise <code>false</code>
     */
    private boolean requestingSecureView(FacesContext context) {
        ExternalContext extContext = context.getExternalContext();       
        String path = extContext.getRequestPathInfo();
        return (!"/login.jsp".equals(path) && !"/create.jsp".equals(path));              
    }
}

16 Respostas

N

alguem?

N

sera que é por causa do facelets??

P

Oi naruto, creio que voce nao deveria fazer o context.responseComplete(), estou enganado?

N

Ola Paulo, boa noite, se eu faço isso ele ja me redireciona logo para a pagina de login e não é isso que eu quero pois quero acessar uma pagina inicial onde qualquer um pode ver e dali tem um menu onde leva ele ate o login e outro problema que aconteceu fazendo isso foi que ele me redireciona para a pagina de login e não sai dali mesmo eu tentando acessar outras opções ele so fica na pagina de login

sabe porque?

Obrigado

R

Naruto:
Ola Paulo, boa noite, se eu faço isso ele ja me redireciona logo para a pagina de login e não é isso que eu quero pois quero acessar uma pagina inicial onde qualquer um pode ver e dali tem um menu onde leva ele ate o login e outro problema que aconteceu fazendo isso foi que ele me redireciona para a pagina de login e não sai dali mesmo eu tentando acessar outras opções ele so fica na pagina de login

sabe porque?

Obrigado

O seu parametro url-pattern do Faces Servlet no arquivo web.xml está utilizando qual formato?

Coloca aqui também a configuração da navegacão do loginEmpresa que está no arquivo faces-config.xml.

R

Naruto:
sera que é por causa do facelets??

Fica tranquilo, o facelets funciona perfeitamente com PhaseListener. :wink:

N
meu web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <context-param>
        <param-name>org.richfaces.CONTROL_SKINNING</param-name>
        <param-value>enable</param-value>
    </context-param>
    <filter>
        <display-name>RichFaces Filter</display-name>
        <filter-name>richfaces</filter-name>
        <filter-class>org.ajax4jsf.Filter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>richfaces</filter-name>
        <servlet-name>Faces Servlet</servlet-name>
        <dispatcher>REQUEST</dispatcher>
        <dispatcher>FORWARD</dispatcher>
        <dispatcher>INCLUDE</dispatcher>
    </filter-mapping>
    <context-param>
        <param-name>javax.faces.STATE_SAVING_METHOD</param-name>
        <param-value>client</param-value>
    </context-param>
    <context-param>
        <param-name>javax.faces.PROJECT_STAGE</param-name>
        <param-value>Development</param-value>
    </context-param>
    <context-param>
        <param-name>javax.faces.DEFAULT_SUFFIX</param-name>
        <param-value>.xhtml</param-value>
    </context-param>
    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.jsf</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>3</session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>
meu faces-fonfig
<?xml version='1.0' encoding='UTF-8'?>

<!-- =========== FULL CONFIGURATION FILE ================================== -->

<faces-config version="1.2" 
              xmlns="http://java.sun.com/xml/ns/javaee"
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd">
   <lifecycle>
        <phase-listener>
            autenticacao.AuthenticationPhaseListenerEmpresa
        </phase-listener>
    </lifecycle>
   <application>
        <view-handler>com.sun.facelets.FaceletViewHandler</view-handler>
    </application>
    <managed-bean>
        <managed-bean-name>EmpresaManagedBean</managed-bean-name>
        <managed-bean-class>apresentacao.managedbean.EmpresaManagedBean</managed-bean-class>
        <managed-bean-scope>session</managed-bean-scope>
    </managed-bean>
    <managed-bean>
        <managed-bean-name>ContatoManagedBean</managed-bean-name>
        <managed-bean-class>apresentacao.managedbean.ContatoManagedBean</managed-bean-class>
        <managed-bean-scope>session</managed-bean-scope>
    </managed-bean>
    <navigation-rule>
        <navigation-case>
            <from-outcome>home</from-outcome>
            <to-view-id>/home.xhtml</to-view-id>
        </navigation-case>
    </navigation-rule>
    <navigation-rule>
        <navigation-case>
            <from-outcome>loginAdministrador</from-outcome>
            <to-view-id>/loginAdministrador/loginAdministrador.xhtml</to-view-id>            
        </navigation-case>
    </navigation-rule>
    <navigation-rule>
        <navigation-case>
            <from-outcome>loginEmpresa</from-outcome>
            <to-view-id>/loginEmpresa/loginEmpresa.xhtml</to-view-id>            
        </navigation-case>
    </navigation-rule>
    <navigation-rule>
        <from-view-id>/empresa/cadastroEmpresa.xhtml</from-view-id>
        <navigation-case>
            <from-action>#{EmpresaManagedBean.inserir}</from-action>
            <from-outcome>sucesso</from-outcome>
            <to-view-id>/empresa/cadastroEmpresaSucesso.xhtml</to-view-id>
        </navigation-case>
    </navigation-rule>
    <navigation-rule>
        <from-view-id>/empresa/cadastroEmpresa.xhtml</from-view-id>
        <navigation-case>
            <from-action>#{EmpresaManagedBean.inserir}</from-action>
            <from-outcome>falha</from-outcome>
            <to-view-id>/empresa/cadastroEmpresa.xhtml</to-view-id>
        </navigation-case>
    </navigation-rule>
    <navigation-rule>
        <from-view-id>/contato/cadastroContato.xhtml</from-view-id>
        <navigation-case>
            <from-action>#{ContatoManagedBean.inserir}</from-action>
            <from-outcome>sucesso</from-outcome>
            <to-view-id>/contato/cadastroContatoSucesso.xhtml</to-view-id>
        </navigation-case>
    </navigation-rule>
    <navigation-rule>
        <from-view-id>/contato/cadastroContato.xhtml</from-view-id>
        <navigation-case>
            <from-action>#{ContatoManagedBean.inserir}</from-action>
            <from-outcome>falha</from-outcome>
            <to-view-id>/contato/cadastroContato.xhtml</to-view-id>
        </navigation-case>
    </navigation-rule>
    <navigation-rule>
        <from-view-id>/home.xhtml</from-view-id>
        <navigation-case>
            <from-action>#{EmpresaManagedBean.montarPaginaCadastroEmpresa}</from-action>
            <from-outcome>sucesso</from-outcome>
            <to-view-id>/empresa/cadastroEmpresa.xhtml</to-view-id>
        </navigation-case>
    </navigation-rule>
    <navigation-rule>
        <from-view-id>/home.xhtml</from-view-id>
        <navigation-case>
            <from-action>#{ContatoManagedBean.montarPaginaCadastroContato}</from-action>
            <from-outcome>sucesso</from-outcome>
            <to-view-id>/contato/cadastroContato.xhtml</to-view-id>
        </navigation-case>
    </navigation-rule>
    <validator>
        <validator-id>emailValidator</validator-id>
        <validator-class>validacao.EmailValidator</validator-class>
    </validator>
</faces-config>

nossa to ficando doidaooo com isso parceiro
:D

R

Certo, quais páginas não precisam ter um usuario autenticado para serem vistas?

Pelo que vi são 3: login.jsp, create.jsp e loginEmpresa.xhtml correto?

N

bom as pagina que podem ser vistas são a home… onde tem uma imagem explicando o sistema, a pagina de cadastro a pagina de login e a pagina de contato essas podem ser vistar sem autenticação…

N

private boolean requestingSecureView(FacesContext context) { ExternalContext extContext = context.getExternalContext(); String path = extContext.getRequestPathInfo(); return (!"/login.jsp".equals(path) && !"/create.jsp".equals(path)); }

o return aqui esta errado era para ser

return (!"/loginEmpresa/loginEmpresa.xhtml".equals(path) && !"/cadastro/cadastroEmpresa.xhtml".equals(path));

masi indenpendente disto ja estava dando erro

R

Naruto:
private boolean requestingSecureView(FacesContext context) { ExternalContext extContext = context.getExternalContext(); String path = extContext.getRequestPathInfo(); return (!"/login.jsp".equals(path) && !"/create.jsp".equals(path)); }

o return aqui esta errado era para ser

return (!"/loginEmpresa/loginEmpresa.xhtml".equals(path) && !"/cadastro/cadastroEmpresa.xhtml".equals(path));

masi indenpendente disto ja estava dando erro

Use a extensão do JSF que você configurou ( *.jsf), tente algo assim:

return (!"loginEmpresa.jsf".equals(path) && !"cadastroEmpresa.jsf".equals(path));
N

obrigado assim que chegar em casa tentarei isso
ai posto o resultado
vlw

N

Boa tarde, Rodrigo, alterei onde vc disse e ficou assim

private boolean requestingSecureView(FacesContext context) { ExternalContext extContext = context.getExternalContext(); String path = extContext.getRequestPathInfo(); return (!"/loginEmpresa/loginEmpresa.jsf".equals(path) && !"/empresa/CadastroEmpresa.jsf".equals(path)); }
porem quando eu executo a aplicação ainda continua mostrando uma pagina em branco e não abre o meu home.jsf
o Paulo sugeriu que eu tirasse o context.responseComplete(); so que se eu faço isso ele me redireciona direto para a pagina de login e não me deixa sair dela… e o que eu quero é que quando abrir aplicação ele mostreu meu home.jsf e nele possa clicar no menu login.jsf e ai sim.

meu web.xml o welcome file é o index.jsp e nesse index tem um jsp:forward que leva para meu home.jsf sera que tem algo a ver?

vlwwwww

N

nossa oq ue estou fazendo de errado sera? tudo que eu precisava era ser redirecionado para meu home e a partir dele acessar uma pagina de login e me logar rsrs

N

mais ninguem passou por isso?

N

Boa noite, consegui resolver sim , mais para isso mudei alguma coisas, pois como eu estava utilizando facelets precisei fazer assim

package autenticacao;

import apresentacao.managedbean.AdministradorManagedBean;
import apresentacao.managedbean.EmpresaManagedBean;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;

/**
 *
 * @author blueyou
 */
public class ListenerAutenticacao implements PhaseListener
{
    private static final String USER_LOGIN_OUTCOME = "home"; //Indica a página para qual deve redirecionar

    @Override
    public void afterPhase(PhaseEvent event)
    {
        FacesContext context = FacesContext.getCurrentInstance();
        if ((usuarioEmpresa(context)) || (usuarioAdministrador(context))) {
            // allow processing of the requested view
            return;
        } else {
            // send the user to the login view
            if (requestingSecureView(context)) {
                FacesContext faces = FacesContext.getCurrentInstance();
                faces.getApplication().getNavigationHandler().handleNavigation(faces,
                    null,
                    USER_LOGIN_OUTCOME);
            }
        }
    }

    /**
     * <p> Verifica se o usuario foi autenticado no contexto da sessao</p>
     */
    private boolean usuarioEmpresa(FacesContext context) {
        ExternalContext extContext = context.getExternalContext();
        return (extContext.getSessionMap().containsKey(EmpresaManagedBean.USER_SESSION_KEY));
    }
    
    private boolean usuarioAdministrador(FacesContext context) {
        ExternalContext extContext = context.getExternalContext();
        return (extContext.getSessionMap().containsKey(AdministradorManagedBean.USER_SESSION_KEY));
    }



    /**
     * <p> Determina se a página requisitada é uma de login, e nesse
     * caso deixa o fluxo seguir sem autenticar.</p>
     *
     */
    private boolean requestingSecureView(FacesContext context) {
        ExternalContext extContext = context.getExternalContext();
        String path = extContext.getRequestServletPath();
        boolean resultado =  (!"/home.jsf".equals(path) && !"/loginEmpresa.jsf".equals(path) && !"/empresaGeral/cadastroEmpresa.jsf".equals(path) && !"/empresaGeral/cadastroEmpresaSucesso.jsf".equals(path) && !"/loginAdministrador.jsf".equals(path) && !"/contato/cadastroContato.jsf".equals(path) && !"/contato/cadastroContatoSucesso.jsf".equals(path) && !"/empresa/exibirProduto.jsf".equals(path));
        return resultado;
    }





    @Override
    public void beforePhase(PhaseEvent event) {
    }

    @Override
    public PhaseId getPhaseId() {
       return PhaseId.RESTORE_VIEW;
    }
}
o resto fiz da mesma forma

flwwwww

Criado 5 de abril de 2010
Ultima resposta 10 de set. de 2010
Respostas 16
Participantes 3