Tuesday, October 2, 2012

@ViewScoped and CDI

If you were working with Seam 2 you sure were familiar with @Scope(ScopeType.PAGE) annotation for your action classes. This scope was used in those cases where the user stayed in the same page working until a redirect (or refresh) was done.

Now, taking a look at CDI you see that there is no out-of-the-box scope that does the same job. JSF 2 provides @ViewScoped but it is incompatible with CDI. You may try the following without success:

import javax.faces.bean.ViewScoped;
import javax.inject.Named;

@Named
@ViewScoped

public class AdministrarUsuariosAction implements Serializable {

Unlike @SessionScoped where you have the CDI proper annotation and the JSF 2 one:

import javax.enterprise.context.SessionScoped;
import javax.faces.bean.SessionScoped;

...for @ViewScoped you only have the JSF 2 one:

import javax.faces.bean.ViewScoped;

So, is there a way we can have a page scope just like in Seam 2? YES

Thanks to Seam 3 Faces module, we are able to use JSF 2 @ViewScoped annotation inside CDI beans. Just add these jars to the pom file:

<dependency>
  <groupid>org.jboss.seam.faces</groupid>
  <artifactid>seam-faces</artifactid>
  <version>3.1.0.Final</version>
</dependency>
  
<dependency>
  <groupid>org.jboss.seam.security</groupid>
  <artifactid>seam-security</artifactid>
  <version>3.1.0.Final</version>
</dependency>

I've tested this configuration under JBoss 7.1.1.Final using the archetype: jboss-javaee6-webapp. I've used this post from Adrian Paredes blog to adapt the archetype to work with JBoss 7.

1 comment:

  1. Thank God Seam 3 is so modular!! Excelent! The old and good page scope...

    ReplyDelete