JSF 2 PreRenderViewEvent example
In JSF 2.0, you can attach a javax.faces.event.PreRenderViewEvent
system event to perform custom task before a view root (JSF page) is display.
Let see a complete PreRenderViewEvent
example below :
1. Managed Bean
Create a normal bean, contains a method signature “public void method-name(ComponentSystemEvent event)“, later you will ask listener to call this method.
In this method, it validate “role” in the current session, if the role is NOT equal to “admin“, then navigate it to outcome “access-denied“.
package com.mkyong; import javax.faces.application.ConfigurableNavigationHandler; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import javax.faces.context.FacesContext; import javax.faces.event.ComponentSystemEvent;
@ManagedBean(name="user") @SessionScopedpublic class UserBean{
public void isAdmin(ComponentSystemEvent event){
FacesContext fc = FacesContext.getCurrentInstance();
if (!"admin".equals(fc.getExternalContext().getSessionMap().get("role"))){
ConfigurableNavigationHandler nav
= (ConfigurableNavigationHandler)
fc.getApplication().getNavigationHandler();
nav.performNavigation("access-denied"); }
} }
2. JSF Page
Now, you use f:event
tag to attach “preRenderView
” system event to “default.xhtml” page.
default.xhtml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" >
<f:event listener="#{user.isAdmin}" type="preRenderView" />
<h:body>
<h1>JSF 2 protected page example</h1>
</h:body> </html>
access-denied.xhtml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" >
<h:body>
<h1>Access Denied!</h1>
</h:body> </html>
3. Demo
Access this page “default.xhtml“, since there is no “role” value in session object, so JSF will navigate to another page “access-denied.xhtml“.
转载于:https://my.oschina.net/yida/blog/69614
上一篇: Redux - example
推荐阅读
-
example2.php
-
Java Web层框架比较—— 比较JSF、Spring MVC、Stripes、Struts 2、Tapestry和Wicket
-
Hadoop 实现协同过滤 (example in
chapter 6) Part 2 -
JSF 2 PreRenderViewEvent example
-
JSF 2 textarea example
-
Lazy JSF Primefaces Datatable Pagination – Part 2
-
example2.php_PHP教程
-
*lyn-example-simple-messaging-pubsub-0.5.0-M2.jar包下载地址,自己也做一个记录,同时也给需要的朋友提供一
-
JSF2中实现国际化
-
example2.php_php基础