跳至主要内容

JSF 2.2: View Action

JSF 2.2: View Action

JSF 2.2 introduced a new view action feature, which had been existed in JBoss Seam 2 and Seam 3 for a long time.
In fact, JSF 2.2 copied the Seam 3 view action exactly.

An example

An example is better than thousands of words.
@Model
public class ViewActionBean {
    
    @Inject Logger log;
    
    private String flag="page1";
    
    public String init(){
        log.info("call init");
        switch(flag){
            case "page1":
                return "page1";
            default:
                return "page2";  
        } 
    }

    public String getFlag() {
        return flag;
    }

    public void setFlag(String flag) {
        this.flag = flag;
    }
    
}

Create a facelets view and use a view action to invoke the init method.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://xmlns.jcp.org/jsf/html" 
      xmlns:f="http://xmlns.jcp.org/jsf/core">
    <f:view>
        <f:metadata>
            <f:viewParam name="flag" value="#{viewActionBean.flag}"/>
            <f:viewAction action="#{viewActionBean.init()}"/>
        </f:metadata>
        <h:head>
            <title>View Action</title>
            <meta name="viewport" content="width=device-width" />
        </h:head>
        <h:body>
            <p> View Action</p>
        </h:body>
    </f:view>
</html>
I created two empty views, page1.xhtml and page2.xhtml for test purpose.
Run this project on Glassfish4, go to http://localhost:8080/ee7-sandbox/viewAction.faces. It will switch to "page1", and if you append a flag=page2 parameter, http://localhost:8080/ee7-sandbox/viewAction.faces?flag=page2, it will redirect to page2 view.
We have preRenderView event listener to load resource for view, why we need view action?
As you see, there are some difference between view action and preRenderView event listener, view action has some advantage which is not available in preRenderView event listener.
  1. view action is a generic JSF action, it has navigation capability, preRenderView has not.
    In preRenderView listener method, you have to use JSF API to navigate to a different view explicitly.
    if("page2".equals(flag)){
            ConfigurableNavigationHandler handler=(ConfigurableNavigationHandler)  
                    FacesContext.getCurrentInstance().getApplication().getNavigationHandler();      
            handler.performNavigation("page2");
    }
    
  2. by default, view action will not be executed on postback phase, but in preRenderView event listener you have to code and overcome it by the following like code in your method.
    if(!FacesContext.getCurrentInstance().isPostback()){
    
    }
    
  3. By default view action will be executed in INVOKE_APPLICATION phase, it has a immediate attribute as other actions in JSF, if it is true it can provides a shortcut of the JSF request lifecycle and executes the action method in APPLY_REQUEST_VALUES phase.
  4. view action also provides a phase attribute which can specify the JSF phase you are going to execute the action.

Before JSF 2.2

Before JSF 2.2, you have some alternatives for the view action.
  1. Seam 3 Faces invented view action, of course it provides the view action feature.
  2. Prettyfaces also provides similar features, which is called url action.
    <url-mapping id="viewAction" outbound="true">
    <pattern value="/viewAction" />
    <view-id value="/viewAction.xhtml" />
    <action>#{viewActionBean.init()}</action>
    </url-mapping>
    
    By default, the action is executed after RESTORE_VIEW and before APPLY_REQUEST_VALUES, which is slightly different from the view action.

The sample codes

The sample codes is hosted on my github.com account, check out the codes and play it yourself.
https://github.com/hantsy/ee7-sandbox
I assume you have installed Glassfish 4 and the latest Oracle Java 7 and NetBeans IDE 7.4 which has good Java EE 7 development support.
NOTE: There is a know issue of JSF reference implementation Mojarra 2.2.0, which can not recognize the newest facelet taglib namespace, http://xmlns.jcp.org/jsf. This issue is fixed in Mojarra 2.2.1, you can get a copy from Maven central repository or Glassfish website.
发表评论

此博客中的热门博文

JPA 2.1: Attribute Converter

JPA 2.1: Attribute Converter If you are using Hibernate, and want a customized type is supported in your Entity class, you could have to write a custom Hibernate Type. JPA 2.1 brings a new feature named attribute converter, which can help you convert your custom class type to JPA supported type. Create an Entity Reuse thePostentity class as example. @Entity @Table(name="POSTS") public class Post implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name="ID") private Long id; @Column(name="TITLE") private String title; @Column(name="BODY") private String body; @Temporal(javax.persistence.TemporalType.DATE) @Column(name="CREATED") private Date created; @Column(name="TAGS") private List<String> tags=new ArrayList<>(); } Create an attribute converter In this example…

Auditing with Hibernate Envers

Auditing with Hibernate Envers The approaches provided in JPA lifecyle hook and Spring Data auditing only track the creation and last modification info of an Entity, but all the modification history are not tracked. Hibernate Envers fills the blank table. Since Hibernate 3.5, Envers is part of Hibernate core project. Configuration Configure Hibernate Envers in your project is very simple, just need to addhibernate-enversas project dependency. <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-envers</artifactId> </dependency> Done. No need extra Event listeners configuration as the early version. Basic Usage Hibernate Envers provides a simple@Auditedannotation, you can place it on an Entity class or property of an Entity. @Audited private String description; If@Auditedannotation is placed on a property, this property can be tracked.

Spring Data Mongo: bridge MongoDB and Spring

Spring Data Mongo: bridge MongoDB and SpringMongoDBis one of the most popular NoSQL products, Spring Data Mongo(Maven archetype id is spring-data-mongodb) tries to provides a simple approach to access MongoDB. Configuration Add the following code fragments in your Spring configuration. <!-- Mongo config --> <mongo:db-factory id="mongoDbFactory" host="localhost" port="27017" dbname="conference-db" /> <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate"> <constructor-arg ref="mongoDbFactory" /> </bean> <mongo:repositories base-package="com.hantsylabs.example.spring.mongo" /> Firstly, declare aDbFactorywhich is responsible for connecting to the MongoDB server. Then, register theMongoTemplateobject which envelop the data operations on MongoDB. Lastly addmongo:repositorieswith an essentialbase-packageattribute, Spring will discovery your d…