primefaces_Primefaces实用程序,RequestContext,EL函数,对话框框架和搜索表达框架

primefaces

Primefaces is a leading JSF library, it provides vast amount of components and facilitates so many kind of utilities and frameworks. This tutorial will highlight the most beneficial utilities and frameworks as well as explain how can we make use all of them more effective in development process.

Primefaces是领先的JSF库,它提供了大量组件,并促进了多种实用程序和框架。 本教程将重点介绍最有用的实用程序框架 ,并说明如何在开发过程中更有效地利用它们。

Primefaces RequestContext (Primefaces RequestContext)

RequestContext is a simple utility that can be obtained similarly like FacesContext and can be used for:

RequestContext是一个简单的实用程序,可以像FacesContext一样获得,可以用于:

  • Adding parameters to ajax callback functions.

    向ajax回调函数添加参数。
  • Help make Runtime update.

    帮助进行运行时更新。
  • Execute JavaScript.

    执行JavaScript。

Let’s first look at the RequestContext API before getting started exploring it.

在开始探索它之前,让我们先看一下RequestContext API。

MethodDescription
isAjaxRequest()Returns a boolean value if current request is a PrimeFaces ajax request.
addCallBackParam(String name, Object value)Adds parameters to ajax callbacks like oncomplete.
update(String clientId);Specifies component(s) to update at runtime.
execute(String script)Executes script after ajax request completes or on page load.
scrollTo(String clientId)Scrolls to the component with given clientId after ajax request completes.
方法 描述
isAjaxRequest() 如果当前请求是PrimeFaces ajax请求,则返回一个布尔值。
addCallBackParam(字符串名称,对象值) 将参数添加到ajax回调中,例如oncomplete。
update(String clientId); 指定要在运行时更新的组件。
执行(字符串脚本) 在ajax请求完成或页面加载后执行脚本。
scrollTo(String clientId) 在ajax请求完成后滚动到具有给定clientId的组件。

Primefaces RequestContext –回调参数 (Primefaces RequestContext – Callback Parameters)

Sometimes you’ve faced cases where you need some values from backing beans in ajax callbacks. Callback parameters are serialized to JSON and provided as an argument in ajax callback for such that access.

有时您会遇到需要从ajax回调中的支持bean中获取一些值的情况。 回调参数被序列化为JSON,并作为ajax回调中的参数提供,以进行此类访问。

index.xhtml

index.xhtml

<html xmlns="https://www.w3.org/1999/xhtml"
		xmlns:ui="https://java.sun.com/jsf/facelets"
		xmlns:h="https://java.sun.com/jsf/html"
		xmlns:f="https://java.sun.com/jsf/core"
		xmlns:p="https://primefaces.org/ui">
	<h:head>
		<script name="jquery/jquery.js" library="primefaces"></script>
		<script>
			function handleComplete(xhr,status,args){
				var isValid = args.isValid;
				alert("isValid RequestContext Parameter Passed Is :: "+isValid);
			}
		</script>
	</h:head>
	<h:form>
		<p:commandButton value="Validate" action="#{utilitiesManagedBean.validate}"
			oncomplete="handleComplete(xhr,status,args)"></p:commandButton>
	</h:form>
	</html>

UtilitiesManagedBean.java

UtilitiesManagedBean.java

package com.journaldev.prime.faces.beans;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

import org.primefaces.context.RequestContext;

@ManagedBean
@SessionScoped
public class UtilitiesManagedBean {
	public String validate(){
		// Acquire Request Context instance
		RequestContext context = RequestContext.getCurrentInstance();
		// Add isValid parameter
		context.addCallbackParam("isValid", true);
		return "";
	}
}

You can send so many parameters as you want, each of yours would be serialized into JSON format. As such, you have the opportunity to send an instance of any type you wish like Person and access its fields like args.person.firstname and so on.

您可以发送任意多个参数,每个参数都将序列化为JSON格式。 这样,您就有机会发送您想要的任何类型的实例(例如Person)并访问其字段(例如args.person.firstname等)。

By default validationFailed callback parameter is added implicitly if validation cycle fails.

默认情况下,如果验证周期失败,则隐式添加validationFailed回调参数。

Primefaces RequestContext –运行时更新 (Primefaces RequestContext – Runtime Updates)

By using RequestContext instance you have the ability to update page’s components conditionally. You can’t update your components in a conditional manner using of command’s update attribute. By using RequestContext’s update method you’re now gladly can do that.

通过使用RequestContext实例,您可以有条件地更新页面的组件。 您不能使用Command的update属性有条件地更新组件。 通过使用RequestContext的update方法,您现在很高兴可以做到这一点。

index2.xhtml

index2.xhtml

<html xmlns="https://www.w3.org/1999/xhtml"
	xmlns:ui="https://java.sun.com/jsf/facelets"
	xmlns:h="https://java.sun.com/jsf/html"
	xmlns:f="https://java.sun.com/jsf/core"
	xmlns:p="https://primefaces.org/ui">
<h:head>
	<script name="jquery/jquery.js" library="primefaces"></script>
</h:head>
<h:form id="form" prependId="false">
	<p:growl id="acceptedMessage"></p:growl>
	<p:growl id="refusedMessage"></p:growl>
	<p:commandButton value="Validate"
		action="#{utilitiesManagedBean.validate}"></p:commandButton>
</h:form>
</html>

UtilitiesManagedBean.java

UtilitiesManagedBean.java

package com.journaldev.prime.faces.beans;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

import org.primefaces.context.RequestContext;

@ManagedBean
@SessionScoped
public class UtilitiesManagedBean {
	public String validate(){
		// Initial value for valid boolean
		boolean valid = false;
		// Do some computation
		if(Math.floor(Math.random()*10) % 2 == 0){
			valid = true;
		}
		// Acquire Request Context instance
		RequestContext context = RequestContext.getCurrentInstance();
		// Add isValid parameter
		context.addCallbackParam("isValid", valid);
		// If valid equal true, render accepted message
		if(valid){
			// Add message into your FacesContext
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Your request is accepeted ! Congrats"));
			// Acquire RequestContext singleton and update desired components
			RequestContext.getCurrentInstance().update("acceptedMessage");
		}
		// else If valid equal false, render refused message
		if(!valid){
			// Add message into your FacesContext
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Your request is refused ! Sorry"));
			// Acquire RequestContext singleton and update desired components
			RequestContext.getCurrentInstance().update("refusedMessage");
		}
		return "";
	}
}

Primefaces RequestContext –执行JavaScript (Primefaces RequestContext – Execute JavaScript)

RequestContext is also provides you a way to execute a JavaScript when the ajax request completes. It’s easier compared to passing callback parameters and execute conditional JavaScript.

RequestContext还为您提供了一种在ajax请求完成时执行JavaScript的方法。 与传递回调参数和执行条件JavaScript相比,它更容易。

index3.xhtml

index3.xhtml

<html xmlns="https://www.w3.org/1999/xhtml"
	xmlns:ui="https://java.sun.com/jsf/facelets"
	xmlns:h="https://java.sun.com/jsf/html"
	xmlns:f="https://java.sun.com/jsf/core"
	xmlns:p="https://primefaces.org/ui">
<h:head>
	<script name="jquery/jquery.js" library="primefaces"></script>
</h:head>
<h:form prependId="false">
	<p:commandButton value="Execute JavaScript"
		action="#{utilitiesManagedBean.executeJavaScript}"></p:commandButton>
	<p:dialog widgetVar="acceptedDialog">
		<p:outputLabel value="Accepted"></p:outputLabel>
	</p:dialog>
	<p:dialog widgetVar="refusedDialog">
		<p:outputLabel value="Refused"></p:outputLabel>
	</p:dialog>
</h:form>
</html>

UtilitiesManagedBean.java

UtilitiesManagedBean.java

package com.journaldev.prime.faces.beans;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

import org.primefaces.context.RequestContext;

@ManagedBean
@SessionScoped
public class UtilitiesManagedBean {
	public String validate(){
		// Initial value for valid boolean
		boolean valid = false;
		// Do some computation
		if(Math.floor(Math.random()*10) % 2 == 0){
			valid = true;
		}
		// Acquire Request Context instance
		RequestContext context = RequestContext.getCurrentInstance();
		// Add isValid parameter
		context.addCallbackParam("isValid", valid);
		// If valid equal true, render accepted message
		if(valid){
			// Add message into your FacesContext
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Your request is accepeted ! Congrats"));
			// Acquire RequestContext singleton and update desired components
			RequestContext.getCurrentInstance().update("acceptedMessage");
		}
		// else If valid equal false, render refused message
		if(!valid){
			// Add message into your FacesContext
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Your request is refused ! Sorry"));
			// Acquire RequestContext singleton and update desired components
			RequestContext.getCurrentInstance().update("refusedMessage");
		}
		return "";
	}

	public String executeJavaScript(){
		// Initial value for valid boolean
		boolean valid = false;
		// Do some computation
		if(Math.floor(Math.random()*10) % 2 == 0){
			valid = true;
		}
		// Hide all of dialogs
		RequestContext.getCurrentInstance().execute("PF('acceptedDialog').hide()");
		RequestContext.getCurrentInstance().execute("PF('refusedDialog').hide()");
		// If valid equal true, render accepted message
		if(valid){
			// Acquire RequestContext singleton and execute wanted JavaScript
			RequestContext.getCurrentInstance().execute("PF('acceptedDialog').show()");
		}
		// else If valid equal false, render refused message
		if(!valid){
			// Acquire RequestContext singleton and execute wanted JavaScript
			RequestContext.getCurrentInstance().execute("PF('refusedDialog').show()");
		}
		return "";
	}
}

Primefaces EL功能 (Primefaces EL Functions)

Primefaces provides a built-in EL expressions that are very helpful in so many cases. Before getting started using EL functions, let’s see the EL functions’ API.

Primefaces提供了内置的EL表达式,在很多情况下都非常有用。 在开始使用EL函数之前,让我们看一下EL函数的API。

FunctionDescription
component(‘id’)Returns clientId of the component with provided server id parameter. This function is useful if you need to work with javascript.
widgetVar(‘id’)Provides the widgetVar of a component in PF(”) format.
功能 描述
组件('id') 返回具有提供的服务器id参数的组件的clientId。 如果您需要使用javascript,此功能非常有用。
widgetVar('id') 以PF(”)格式提供组件的widgetVar。

Primefaces EL功能–组件和WidgetVar (Primefaces EL Functions – Component & WidgetVar)

Primefaces provides you so easy way for locating components either by using their identifiers or their WidgetVars.

Primefaces提供了一种使用组件标识符或WidgetVars轻松定位组件的简便方法。

index4.xhtml

index4.xhtml

<html xmlns="https://www.w3.org/1999/xhtml"
	xmlns:ui="https://java.sun.com/jsf/facelets"
	xmlns:h="https://java.sun.com/jsf/html"
	xmlns:f="https://java.sun.com/jsf/core"
	xmlns:p="https://primefaces.org/ui">
<h:head>
	<script name="jquery/jquery.js" library="primefaces"></script>
</h:head>
<h:form id="form">
	<p:outputLabel id="text" value="This component accessed by EL function and it's ID is: #{p:component('text')}"></p:outputLabel>
	<p:dialog id="dlg">
		<p:outputLabel value="Dialog Component"></p:outputLabel>
	</p:dialog>
	<p:separator/>
	<p:commandButton id="action2" value="Show Dialog" type="button" onclick="#{p:widgetVar('form:dlg')}.show()"></p:commandButton>
</h:form>
</html>

Primefaces异常处理程序 (Primefaces Exception Handler)

We’ve clarified Exception Handler intensively in Ajax Behavior Tutorial.

我们已经在Ajax Behavior Tutorial中集中阐明了Exception Handler。

Primefaces语言环境 (Primefaces Locales)

We’ve clarified Primefaces Locales intensively in Calendar Component Tutorial.

我们在日历组件教程中集中阐明了Primefaces语言环境。

Primefaces对话框架 (Primefaces Dialog Framework)

Dialog framework (DF) is used to open an external XHTML page in a dialog that’s generated dynamically at Runtime. This is little bit different from old fashion we are used to show a dialog. Old way requires defining a p:dialog inside an XHTML page and make use of show/hide for getting dialog controlled (Shown/hidden). This time we will use a DF API that in which a programmatic API will be used for creating and destroying the dialogs instantly and at Runtime. Following simple example that shows you dialog created and destroyed programmatically.

对话框框架(DF)用于在运行时动态生成的对话框中打开外部XHTML页面。 这与我们用来显示对话框的旧样式有点不同。 旧方法需要在XHTML页面中定义p:dialog并利用show / hide来控制对话框(显示/隐藏)。 这次,我们将使用DF API,其中将使用编程API来在运行时立即创建和销毁对话框。 下面的简单示例向您显示以编程方式创建和销毁的对话框。

faces-config.xml

faces-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<faces-config xmlns="https://xmlns.jcp.org/xml/ns/javaee"
	xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="https://xmlns.jcp.org/xml/ns/javaee https://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd"
	version="2.2">
	<application>
		<action-listener>org.primefaces.application.DialogActionListener</action-listener>
		<navigation-handler>org.primefaces.application.DialogNavigationHandler</navigation-handler>
		<view-handler>org.primefaces.application.DialogViewHandler</view-handler>
	</application>
</faces-config>

dialogInitiator.xhtml

dialogInitiator.xhtml

<html xmlns="https://www.w3.org/1999/xhtml"
	xmlns:ui="https://java.sun.com/jsf/facelets"
	xmlns:h="https://java.sun.com/jsf/html"
	xmlns:f="https://java.sun.com/jsf/core"
	xmlns:p="https://primefaces.org/ui">
<h:head>
	<script name="jquery/jquery.js" library="primefaces"></script>
</h:head>
<h:form id="form">
	<p:commandButton value="Show Dialog" action="#{dialogFrameworkManagedBean.showDialog}"></p:commandButton>
</h:form>
</html>

externalXHTML.xhtml

externalXHTML.xhtml

<html xmlns="https://www.w3.org/1999/xhtml"
	xmlns:ui="https://java.sun.com/jsf/facelets"
	xmlns:h="https://java.sun.com/jsf/html"
	xmlns:f="https://java.sun.com/jsf/core"
	xmlns:p="https://primefaces.org/ui">
<h:head>
	<script name="jquery/jquery.js" library="primefaces"></script>
</h:head>
<h:form id="form">
	<p:outputLabel value="This XHTML page will be dispalyed/hidden via using of DF API"></p:outputLabel>
</h:form>
</html>

DialogFrameworkManagedBean.java

DialogFrameworkManagedBean.java

package com.journaldev.prime.faces.beans;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

import org.primefaces.context.RequestContext;

@ManagedBean
@SessionScoped
public class DialogFrameworkManagedBean {

	public String showDialog(){
		RequestContext.getCurrentInstance().openDialog("externalXHTML");
		return "";
	}
}

As you can provide an Optional arguments that help you make additional control for your dialog properties. Following sample shows you how can you provide such that arguments and a figured Table for the properties that may be controlled.

您可以提供Optional参数,以帮助您对对话框属性进行其他控制。 以下示例显示了如何为可控制的属性提供参数和数字表。

dialogInitiator.xhtml

dialogInitiator.xhtml

<html xmlns="https://www.w3.org/1999/xhtml"
	xmlns:ui="https://java.sun.com/jsf/facelets"
	xmlns:h="https://java.sun.com/jsf/html"
	xmlns:f="https://java.sun.com/jsf/core"
	xmlns:p="https://primefaces.org/ui">
<h:head>
	<script name="jquery/jquery.js" library="primefaces"></script>
</h:head>
<h:form id="form">
	<p:commandButton value="Show Dialog - Basic" action="#{dialogFrameworkManagedBean.showDialog}"></p:commandButton>
	<p:commandButton value="Show Dialog - Additional Properties" action="#{dialogFrameworkManagedBean.showDialogWithAdditionalArg}"></p:commandButton>
</h:form>
</html>

externalXHTML.xhtml

externalXHTML.xhtml

<html xmlns="https://www.w3.org/1999/xhtml"
	xmlns:ui="https://java.sun.com/jsf/facelets"
	xmlns:h="https://java.sun.com/jsf/html"
	xmlns:f="https://java.sun.com/jsf/core"
	xmlns:p="https://primefaces.org/ui">
<h:head>
	<script name="jquery/jquery.js" library="primefaces"></script>
</h:head>
<h:form id="form">
	<p:outputLabel value="This XHTML page will be dispalyed/hidden via using of DF API"></p:outputLabel>
</h:form>
</html>

DialogFrameworkManagedBean.java

DialogFrameworkManagedBean.java

package com.journaldev.prime.faces.beans;

import java.util.HashMap;
import java.util.Map;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

import org.primefaces.context.RequestContext;

@ManagedBean
@SessionScoped
public class DialogFrameworkManagedBean {

	public String showDialog(){
		RequestContext.getCurrentInstance().openDialog("externalXHTML");
		return "";
	}

	public String showDialogWithAdditionalArg(){
		// Fill in properties
		Map<String,Object> properties  = new HashMap<String,Object>();
		properties.put("modal", true);
		properties.put("resizable", true);
		properties.put("draggable", true);
		properties.put("width", 400);
		properties.put("height", 400);
		RequestContext.getCurrentInstance().openDialog("externalXHTML",properties,null);
		return "";
	}

}

Find below all of those properties that you may want to provide.

在您可能想要提供的所有这些属性下面查找。

NameDefaultTypeDescription
modal0BooleanControls modality of the dialog.
resizable1BooleanWhen enabled, makes dialog resizable.
draggable1BooleanWhen enabled, makes dialog draggable.
widthautoIntegerWidth of the dialog.
heightautoIntegerHeight of the dialog.
contentWidth640IntegerWidth of the dialog content.
contentHeightautoIntegerHeight of the dialog content.
closabletrueBooleanWhether the dialog can be closed or not.
名称 默认 类型 描述
情态的 0 布尔型 控制对话框的模式。
可调整大小 1个 布尔型 启用后,可调整对话框的大小。
可拖动的 1个 布尔型 启用后,可使对话框可拖动。
宽度 汽车 整数 对话框的宽度。
高度 汽车 整数 对话框的高度。
contentWidth 640 整数 对话框内容的宽度。
contentHeight 汽车 整数 对话框内容的高度。
可关闭 真正 布尔型 对话框是否可以关闭。

Primefaces对话框架–数据通信 (Primefaces Dialog Framework – Data Communication)

You can pass data back into the parent page that triggered the dialog to be displayed.

您可以将数据传回到触发该对话框显示的父页面。

dataInitiator.xhtml

dataInitiator.xhtml

<html xmlns="https://www.w3.org/1999/xhtml"
	xmlns:ui="https://java.sun.com/jsf/facelets"
	xmlns:h="https://java.sun.com/jsf/html"
	xmlns:f="https://java.sun.com/jsf/core"
	xmlns:p="https://primefaces.org/ui">
<h:head>
	<script name="jquery/jquery.js" library="primefaces"></script>
</h:head>
<h:form id="form">
	<p:growl id="growl" showDetail="true" showSummary="true"></p:growl>
	<p:commandButton value="Show Dialog - Basic" action="#{dialogFrameworkManagedBean.showDialog}"></p:commandButton>
	<p:commandButton value="Show Dialog - Additional Properties" action="#{dialogFrameworkManagedBean.showDialogWithAdditionalArg}"></p:commandButton>
	<p:commandButton value="Show Employees Dialog" action="#{dialogFrameworkManagedBean.showEmployeesDialog}">
		<p:ajax event="dialogReturn" listener="#{dialogFrameworkManagedBean.onEmployeeChosen}" update="growl" />
	</p:commandButton>
</h:form>
</html>

employee.xhtml

employee.xhtml

<html xmlns="https://www.w3.org/1999/xhtml"
	xmlns:ui="https://java.sun.com/jsf/facelets"
	xmlns:h="https://java.sun.com/jsf/html"
	xmlns:f="https://java.sun.com/jsf/core"
	xmlns:p="https://primefaces.org/ui">
<h:head>
	<script name="jquery/jquery.js" library="primefaces"></script>
</h:head>
<h:form id="form">
	<p:dataTable value="#{dialogFrameworkManagedBean.employees}" var="employee">
		<p:column headerText="Employee ID">
			<p:outputLabel value="#{employee.employeeId}"></p:outputLabel>
		</p:column>
		<p:column headerText="Employee Name">
			<p:outputLabel value="#{employee.employeeName}"></p:outputLabel>
		</p:column>
		<p:column headerText="Select Employee">
			<p:commandButton icon="ui-icon-search" action="#{dialogFrameworkManagedBean.selectEmployeeFromDialog(employee)}" />
       	</p:column>
	</p:dataTable>
</h:form>
</html>

DialogFrameworkManagedBean.java

DialogFrameworkManagedBean.java

package com.journaldev.prime.faces.beans;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

import org.primefaces.context.RequestContext;
import org.primefaces.event.SelectEvent;

@ManagedBean
@SessionScoped
public class DialogFrameworkManagedBean {
	private List<Employee> employees = new ArrayList<Employee>();

	public List<Employee> getEmployees() {
		return employees;
	}

	public void setEmployees(List<Employee> employees) {
		this.employees = employees;
	}

	public String showDialog(){
		RequestContext.getCurrentInstance().openDialog("externalXHTML");
		return "";
	}

	public String showDialogWithAdditionalArg(){
		// Fill in properties
		Map<String,Object> properties  = new HashMap<String,Object>();
		properties.put("modal", true);
		properties.put("resizable", true);
		properties.put("draggable", true);
		properties.put("width", 400);
		properties.put("height", 400);
		RequestContext.getCurrentInstance().openDialog("externalXHTML",properties,null);
		return "";
	}

	public String showEmployeesDialog(){
		this.employees = new ArrayList<Employee>();
		for(int i = 1 ; i < 10 ; i++){
			Employee employee = new Employee();
			employee.setEmployeeId(i);
			employee.setEmployeeName("Employee"+i);
			employee.setEmployeeAge(String.valueOf(21+i));
			this.employees.add(employee);
		}
		RequestContext.getCurrentInstance().openDialog("employees");
		return "";
	}

	public void selectEmployeeFromDialog(Employee employee) {
        RequestContext.getCurrentInstance().closeDialog(employee);
    }

	public void onEmployeeChosen(SelectEvent event){
		Employee employee = (Employee) event.getObject();
        FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO,
        		"Employee Selected",
        		"Id:" + employee.getEmployeeId()+"\n"+
        		"Name:"+employee.getEmployeeName());
        FacesContext.getCurrentInstance().addMessage(null, message);
	}

	public class Employee {
		private int employeeId;
		private String employeeName;
		private String employeeAge;
		public int getEmployeeId() {
			return employeeId;
		}
		public void setEmployeeId(int employeeId) {
			this.employeeId = employeeId;
		}
		public String getEmployeeName() {
			return employeeName;
		}
		public void setEmployeeName(String employeeName) {
			this.employeeName = employeeName;
		}
		public String getEmployeeAge() {
			return employeeAge;
		}
		public void setEmployeeAge(String employeeAge) {
			this.employeeAge = employeeAge;
		}
	}

}

Here’s detailed explanation for code listed above:

这是上面列出的代码的详细说明:

  • Parent page that contains a triggered action should provide a dialogReturn ajax event.

    包含触发操作的父页面应提供一个dialogReturn ajax事件。
  • RequestContext.getCurrentInstance().closeDialog has been used with a data returned back conventionally. If you’ve tried to use it without returned data, an exception will be got.

    RequestContext.getCurrentInstance()。closeDialog已用于按常规方式返回的数据。 如果您尝试在不返回数据的情况下使用它,则会出现异常。
  • Since jsf 2, dataTable component has provided a newly way for specifying selected employee. That is by sending the selected employee directly via using of selection trigger.

    从jsf 2开始,dataTable组件提供了一种新方法来指定选定的雇员。 即通过使用选择触发器直接发送选定的员工。
  • Both of p:commandButton and p:commandLink do support for dialogReturn event.

    p:commandButton和p:commandLink都支持dialogReturn事件。

Primefaces对话框框架–对话框消息 (Primefaces Dialog Framework – Dialog Messages)

It’s well-known how can you add a messages into your view or even a dialog using a standard FacesContext – addMessage way. Dialog framework has provided a new way of adding a messages into your opened dialog. Following sample will help you getting your messages shown using a non-traditional way.

众所周知,如何使用标准FacesContext – addMessage方式将消息添加到视图甚至对话框中。 对话框框架提供了一种将消息添加到打开的对话框中的新方法。 以下示例将帮助您以非传统方式显示您的消息。

employees.xhtml

employees.xhtml

<html xmlns="https://www.w3.org/1999/xhtml"
	xmlns:ui="https://java.sun.com/jsf/facelets"
	xmlns:h="https://java.sun.com/jsf/html"
	xmlns:f="https://java.sun.com/jsf/core"
	xmlns:p="https://primefaces.org/ui">
<h:head>
	<script name="jquery/jquery.js" library="primefaces"></script>
</h:head>
<h:form id="form">
	<p:dataTable value="#{dialogFrameworkManagedBean.employees}" var="employee">
		<p:column headerText="Employee ID">
			<p:outputLabel value="#{employee.employeeId}"></p:outputLabel>
		</p:column>
		<p:column headerText="Employee Name">
			<p:outputLabel value="#{employee.employeeName}"></p:outputLabel>
		</p:column>
		<p:column headerText="Select Employee">
			<p:commandButton icon="ui-icon-search" action="#{dialogFrameworkManagedBean.selectEmployeeFromDialog(employee)}" />
       	</p:column>
	</p:dataTable>
	<p:commandButton value="Show Message" action="#{dialogFrameworkManagedBean.showMessage}"></p:commandButton>
</h:form>
</html>

DialogFrameworkManagedBean.java

DialogFrameworkManagedBean.java

package com.journaldev.prime.faces.beans;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

import org.primefaces.context.RequestContext;
import org.primefaces.event.SelectEvent;

@ManagedBean
@SessionScoped
public class DialogFrameworkManagedBean {
	private List<Employee> employees = new ArrayList<Employee>();

	public List<Employee> getEmployees() {
		return employees;
	}

	public void setEmployees(List<Employee> employees) {
		this.employees = employees;
	}

	public String showDialog(){
		RequestContext.getCurrentInstance().openDialog("externalXHTML");
		return "";
	}

	public String showDialogWithAdditionalArg(){
		// Fill in properties
		Map<String,Object> properties  = new HashMap<String,Object>();
		properties.put("modal", true);
		properties.put("resizable", true);
		properties.put("draggable", true);
		properties.put("width", 400);
		properties.put("height", 400);
		RequestContext.getCurrentInstance().openDialog("externalXHTML",properties,null);
		return "";
	}

	public String showEmployeesDialog(){
		this.employees = new ArrayList<Employee>();
		for(int i = 1 ; i < 10 ; i++){
			Employee employee = new Employee();
			employee.setEmployeeId(i);
			employee.setEmployeeName("Employee"+i);
			employee.setEmployeeAge(String.valueOf(21+i));
			this.employees.add(employee);
		}
		RequestContext.getCurrentInstance().openDialog("employees");
		return "";
	}

	public void selectEmployeeFromDialog(Employee employee) {
        RequestContext.getCurrentInstance().closeDialog(employee);
    }

	public void onEmployeeChosen(SelectEvent event){
		Employee employee = (Employee) event.getObject();
        FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO,
        		"Employee Selected",
        		"Id:" + employee.getEmployeeId()+"\n"+
        		"Name:"+employee.getEmployeeName());
        FacesContext.getCurrentInstance().addMessage(null, message);
	}

	public String showMessage(){
		RequestContext.getCurrentInstance().showMessageInDialog(new FacesMessage("Message Is Shown"));
		return "";
	}

	public class Employee {
		private int employeeId;
		private String employeeName;
		private String employeeAge;
		public int getEmployeeId() {
			return employeeId;
		}
		public void setEmployeeId(int employeeId) {
			this.employeeId = employeeId;
		}
		public String getEmployeeName() {
			return employeeName;
		}
		public void setEmployeeName(String employeeName) {
			this.employeeName = employeeName;
		}
		public String getEmployeeAge() {
			return employeeAge;
		}
		public void setEmployeeAge(String employeeAge) {
			this.employeeAge = employeeAge;
		}
	}
}
  • Adding of new messages into your opened dialog can be done through using of RequestContext.getCurrentInstance().showMessage(“your_msg”) code.

    可以使用RequestContext.getCurrentInstance()。showMessage(“ your_msg”)代码将新消息添加到打开的对话框中。

Primefaces搜索表达框架 (Primefaces Search Expression Framework)

We’ve introduced several tutorials that are using search expression framework. But it’s worth to take a deep look to know more about it. Core JSF component referencing is based on component identifiers only with basic keyword support. Primefaces search expression framework provides both server side and client side extensions to make it easier to reference components. Let’s see all the keywords that you can use to reference the components that might be located into your view.

我们已经介绍了一些使用搜索表达式框架的教程。 但是值得深入了解以了解更多信息。 核心JSF组件引用仅基于具有基本关键字支持的组件标识符。 Primefaces搜索表达框架提供了服务器端和客户端扩展,从而使引用组件变得更加容易。 让我们查看所有可用于引用可能位于视图中的组件的关键字。

KeywordTypeDescription
@thisStandardCurrent component.
@allStandardWhole view.
@formStandardClosest ancestor form of current component.
@noneStandardNo component.
@namingcontainerPrimeFacesClosest ancestor naming container of current component.
@parentPrimeFacesParent of the current component.
@compositePrimeFacesClosest composite component ancestor.
@child(n)PrimeFacesnth child.
@previousPrimeFacesPrevious sibling.
@nextPrimeFacesNext sibling.
@widgetVar(name)PrimeFacesComponent with given widgetVar.
关键词 类型 描述
@这个 标准 当前组件。
@所有 标准 整个视图。
@形成 标准 当前组件的最接近祖先形式。
@没有 标准 无组件。
@namingcontainer 素颜 当前组件的最近祖先命名容器。
@父母 素颜 当前组件的父级。
@综合 素颜 最接近的复合组件祖先。
@child(n) 素颜 第n个孩子。
@以前 素颜 以前的兄弟姐妹。
@下一个 素颜 下一个兄弟姐妹。
@widgetVar(名称) 素颜 具有指定的widgetVar的组件。

Let’s see now some of examples for how can we leverage some of these keywords for locating wanted components on a page.

现在让我们看一些示例,说明如何利用这些关键字在页面上查找所需组件。

SEF.xhtml

SEF.xhtml

<html xmlns="https://www.w3.org/1999/xhtml"
	xmlns:ui="https://java.sun.com/jsf/facelets"
	xmlns:h="https://java.sun.com/jsf/html"
	xmlns:f="https://java.sun.com/jsf/core"
	xmlns:p="https://primefaces.org/ui">
<h:head>
	<script name="jquery/jquery.js" library="primefaces"></script>
</h:head>
	<h:form>
		<p:growl id="message"></p:growl>
		<p:outputLabel id="output1" value="Enter Username">#{' '}</p:outputLabel><p:inputText id="username" value="#{searchExtensionFramework.username}"></p:inputText>
		<p:separator/>
		<p:outputLabel id="output2" value="Enter Password">#{' '}</p:outputLabel><p:password id="password" value="#{searchExtensionFramework.password}"></p:password>
		<p:separator/>
		<p:commandButton value="Reference Message Component"
			action="#{searchExtensionFramework.doAction}"
			process="@this" update="@form:@child(0)"></p:commandButton>
	</h:form>
</html>

SearchExtensionFramework.java

SearchExtensionFramework.java

package com.journaldev.prime.faces.beans;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

@ManagedBean
@SessionScoped
public class SearchExtensionFramework {
	private String username = "";
	private String password = "";
	
	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String doAction(){
		FacesContext.getCurrentInstance().addMessage(null, 
				new FacesMessage("Growl Component Updated and Referenced By Using SEF","Username: "
						+	this.username	+	" :: Password: "	+	password));
		return "";
	}
}
  • We’ve referenced the form using of @form before getting growl component referenced by using of @child(0).

    在使用@child(0)引用咆哮组件之前,我们已经使用@form引用了表单。
  • @form:@child(0) is know as composite expressions.

    @form:@child(0)被称为复合表达式。

SEF.xhtml

SEF.xhtml

<html xmlns="https://www.w3.org/1999/xhtml"
	xmlns:ui="https://java.sun.com/jsf/facelets"
	xmlns:h="https://java.sun.com/jsf/html"
	xmlns:f="https://java.sun.com/jsf/core"
	xmlns:p="https://primefaces.org/ui">
<h:head>
	<script name="jquery/jquery.js" library="primefaces"></script>
</h:head>
	<h:form>
		<p:growl widgetVar="message"></p:growl>
		<p:outputLabel id="output1" value="Enter Username">#{' '}</p:outputLabel><p:inputText id="username" value="#{searchExtensionFramework.username}"></p:inputText>
		<p:separator/>
		<p:outputLabel id="output2" value="Enter Password">#{' '}</p:outputLabel><p:password id="password" value="#{searchExtensionFramework.password}"></p:password>
		<p:separator/>
		<p:commandButton value="Reference Message Component"
			action="#{searchExtensionFramework.doAction}"
			process="@this" update="@widgetVar(message)"></p:commandButton>
	</h:form>
</html>

You will get the same result when @widgetVar alone is used.

当单独使用@widgetVar时,您将获得相同的结果。

Primefaces搜索表达框架– Primefaces选择器 (Primefaces Search Expression Framework – Primefaces Selectors)

Primefaces integrates jQuery Selector API with JSF component referencing model so that referencing can be done using of jQuery Selector API instead of code id based JSF model.

Primefaces将jQuery Selector API与JSF组件引用模型集成在一起,因此可以使用jQuery Selector API代替基于代码ID的JSF模型来进行引用。

SEF.xhtml

SEF.xhtml

<html xmlns="https://www.w3.org/1999/xhtml"
	xmlns:ui="https://java.sun.com/jsf/facelets"
	xmlns:h="https://java.sun.com/jsf/html"
	xmlns:f="https://java.sun.com/jsf/core"
	xmlns:p="https://primefaces.org/ui">
<h:head>
	<script name="jquery/jquery.js" library="primefaces"></script>
</h:head>
	<h:form>
		<p:growl></p:growl>
		<p:outputLabel id="output1" value="Enter Username">#{' '}</p:outputLabel><p:inputText id="username" value="#{searchExtensionFramework.username}"></p:inputText>
		<p:separator/>
		<p:outputLabel id="output2" value="Enter Password">#{' '}</p:outputLabel><p:password id="password" value="#{searchExtensionFramework.password}"></p:password>
		<p:separator/>
		<p:commandButton value="Reference Message Component"
			action="#{searchExtensionFramework.doAction}"
			process="@this" update="@(form:first)"></p:commandButton>
	</h:form>
</html>
  • You will get the same result when you use a JQuery expression form. Let’s assume that your inputs have a style .myStyle; by using of @(.myStyle) you would be able to specify the component(s) that have it.

    当您使用JQuery表达式形式时,您将获得相同的结果。 假设您的输入具有.myStyle样式; 通过使用@(.myStyle)您将可以指定具有它的组件。
  • If you’ve used @(:input) in the update or process, you’re trying to update or process all input components that you have.

    如果在更新或过程中使用了@(:input) ,则尝试更新或处理您拥有的所有输入组件。
  • You can combine between Primefaces and jQuery referencing techniques.

    您可以在Primefaces和jQuery引用技术之间进行组合。

摘要 (Summary)

Primefaces is a leading implementation of JSF. It provides you a huge amount of accompanies utilities, frameworks and enhancements that make development tasks more easier than using otherwise implementation. This tutorial have highlighted part of these utilities and frameworks. Contribute us by commenting below and find downloaded source code.

Primefaces是JSF的领先实现。 它为您提供了大量附带的实用程序,框架和增强功能,这些功能使开发任务比使用其他实现更容易。 本教程重点介绍了这些实用程序和框架的一部分。 通过在下面评论来贡献我们,并找到下载的源代码。

翻译自: https://www.journaldev.com/4056/primefaces-utilities-requestcontext-el-functions-dialog-framework-search-expression-framework

primefaces

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值