Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Injecting FacesContext with CDI

Tags:

jsf

cdi

I have my Bean:

import java.io.Serializable;

import javax.enterprise.context.SessionScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.EntityManager;

import br.com.dropper.web.dao.UsuarioDAO;
import br.com.dropper.web.model.Usuario;
import br.com.dropper.web.util.JpaUtil;

@Named
@SessionScoped
public class LoginBean implements Serializable {

    private static final long serialVersionUID = 1L;

    @Inject
    private FacesContext context;

    @Inject
    private Usuario usuario;


    //TODO: Persistencia e Transacao controladas por EJB
    private EntityManager em = new JpaUtil().getEntityManager();
    private UsuarioDAO usuarioDAO = new UsuarioDAO(em);



    public Usuario getUsuario() {
        return usuario;
    }

    public String autenticar() {

        Usuario usuario = usuarioDAO.obterUsuarioPorEmail(this.usuario);

        if (usuario == null) {
            context.addMessage(null, new FacesMessage("Usuario não encontrado."));
            context.getExternalContext().getFlash().setKeepMessages(true);
            return "login?faces-redirect=true";
        } else {
            context.getExternalContext().getSessionMap().put("usuarioLogado", usuario);
            return "dashboardImagem.xhtml?faces-redirect=true";
        }
    }

    public String cadastrarUsuario() {
        System.out.println("Redirecionando para cadastroUsuario.xhtml");
        return "cadastroUsuario.xhtml?faces-redirect=true";
    }

    public String logout() {
        context.getExternalContext().getSessionMap().remove("usuarioLogado");
        context.getExternalContext().invalidateSession();
        return "login.xhtml?faces-redirect=true";

    }

}

And my Factory:

package br.com.dropper.web.factory;

import java.io.Serializable;

import javax.enterprise.inject.Produces;
import javax.faces.context.FacesContext;
import javax.faces.view.ViewScoped;

public class FacesContextFactory implements Serializable{

    private static final long serialVersionUID = 1L;

    @Produces
    @ViewScoped
    public FacesContext getFacesContext(){
        return FacesContext.getCurrentInstance();
    }

}

When i run my application, im getting this exception:

Caused by: org.jboss.weld.exceptions.IllegalProductException: WELD-000053: Producers cannot declare passivating scope and return a non-serializable class: Producer for Producer Method [FacesContext] with qualifiers [@Any @Default] declared as [[BackedAnnotatedMethod] @Produces @ViewScoped public br.com.dropper.web.factory.FacesContextFactory.getFacesContext()] declared on Managed Bean [class br.com.dropper.web.factory.FacesContextFactory] with qualifiers [@Any @Default]
    at br.com.dropper.web.factory.FacesContextFactory.getFacesContext(FacesContextFactory.java:16)

And when i change the produces method to @RequestScoped, my FacesContext it's inject only one time, and in my second page xhtml, i get a nullpointer =(

UPDATE: pom

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>br.com.dropper</groupId>
    <artifactId>dropper-web</artifactId>
    <version>0.1</version>
    <packaging>war</packaging>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>javax</groupId>
                <artifactId>javaee-api</artifactId>
                <version>7.0</version>
                <scope>provided</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>

        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <scope>provided</scope>
        </dependency>

        <!-- <dependency>
            <groupId>dropper-web</groupId>
            <artifactId>postgresql</artifactId>
            <version>9.4.1212</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/src/main/webapp/WEB-INF/lib/postgresql-9.4.1212.jre6.jar</systemPath>
        </dependency>  -->

        <dependency>
            <groupId>dropper-web</groupId>
            <artifactId>bootstrap</artifactId>
            <version>1.0.10</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/src/main/webapp/WEB-INF/lib/bootstrap-1.0.10.jar</systemPath>
        </dependency>

        <dependency>
            <groupId>dropper-web</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.5</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/src/main/webapp/WEB-INF/lib/commons-io-2.5.jar</systemPath>
        </dependency>

        <dependency>
            <groupId>dropper-web</groupId>
            <artifactId>cupertino</artifactId>
            <version>1.0.10</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/src/main/webapp/WEB-INF/lib/cupertino-1.0.10.jar</systemPath>
        </dependency>


        <dependency>
            <groupId>dropper-web</groupId>
            <artifactId>primefaces-6.0</artifactId>
            <version>6.0</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/src/main/webapp/WEB-INF/lib/primefaces-6.0.jar</systemPath>
        </dependency>

    </dependencies>


    <build>
        <finalName>dropper-web</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

Att

like image 556
deveduardo Avatar asked Jan 19 '17 00:01

deveduardo


1 Answers

The FacesContext itself is indeed not Serializable. And, more important, it is definitely not @ViewScoped. It's actually shorter than @RequestScoped, but until JSF 2.3 is released which comes with improved CDI support so you could just @Inject FacesContext without having a custom producer, you could less or more safely use @Produces @RequestScoped instead.

@Produces
@RequestScoped
public FacesContext getFacesContext(){
    return FacesContext.getCurrentInstance();
}

One case where this would still fail is when you explicitly perform a forward within the same request using RequestDispatcher#forward() or ExternalContext#dispatch(). You will then face java.lang.IllegalStateException at com.sun.faces.context.FacesContextImpl.assertNotReleased. This is however a very rare case and usually only performed in a badly designed (ajax) exception handler. See also a.o. using ExternalContext.dispatch in JSF error handler causes corrupt page rendering.

like image 65
BalusC Avatar answered Nov 08 '22 23:11

BalusC