Adding Ajax to JavaServer Faces Technology With Dynamic Faces

Article

Adding Ajax to JavaServer Faces Technology With Dynamic Faces

 

This article shows how to use Project Dynamic Faces, included in the new Sun Web Developer Pack, to add first-class Ajax support to your JavaServer Faces technology-based application.

Beginning with an existing sample application, Virtual Trainer, from the book that the article's author wrote with Chris Schalk, JavaServer Faces: The Complete Reference, this article will show you how to add Ajax behavior to two of that application's pages. This example will illustrate two usage patterns for Project Dynamic Faces and also provide a springboard for discussing the Ajax techniques that Dynamic Faces employs.

First, this article will go through the Virtual Trainer application and call out the places where you will add Ajax features.

The application's welcome page contains two links at the upper right: Register and Login. The Sign Up Today! link at the bottom of the page points to the same page as the Register page. Click Register.

The screen capture in Figure 1 shows the non-Ajax version of the registration page. As you can see, this is a garden-variety JavaServer Faces technology-based page. Fill out the form but use

jake

for the Userid text field, and submit the form.

non-ajax-register.png

Once you get past the validation errors, you will see the message

Userid jake already exists! Please choose another.

Wouldn't it be nice if there were a button next to the Userid field that would allow the user to fire an Ajax request off to the server, sending only the user ID and checking only whether that user ID is available? With a few lines of code, you can create this functionality.

Now click the Login link in the application, and use

jake

as both the user ID and the password. Once logged in, you will see a table of training events, as shown in Figure 2. Choose one training event by clicking the Select link at the right of the desired row.

event-information600.png

You now see a page allowing the trainer, jake, to advise the trainee on how to train for the selected event. For every training session for which the user has selected Completed in the table, the user will be able to type in the Personal Notes field only if the Completed checkbox is not checked. If you deselect a Completed checkbox and click the Update Event button, the Personal Notes field becomes editable.

But why bother with the extra step of clicking the Update Event button? With a few lines of code, you can remove the Update Event button and enable the application to update the form with Ajax whenever the user selects the checkbox. Download the Java Platform, Enterprise Edition (Java EE) SDK or the Platform Edition of Sun Java System Application Server version 9.0 or 9.1, and install and configure it according to the instructions that come with the download. Also download the Sun Web Developer Pack (SWDP) and follow the instructions to install it on top of the SDK or Application Server. The rest of this article assumes you are using NetBeans IDE 5.5 to build and run the example, though you need not do so.

For maximum ease, install the NetBeans IDE modules that come with the SWDP according to the instructions provided in the SWDP download. Doing this will make it easy to add Dynamic Faces support to your application.

Now download the source bundle for this article and the original source for the Virtual Trainer application. Once you have the NetBeans IDE and the SWDP modules installed, open the Virtual Trainer NetBeans project from the article download. Right click on the Virtual Trainer project and choose Properties. Highlight the Libraries tab and make sure that

SWDP-jsf-extensions

is in the list.

Finally, modify the application's

web.xml

file to enable the Ajax life cycle supplied with Dynamic Faces. Locate the

<servlet>

declaration for the

<servlet-class>

javax.faces.webapp.FacesServlet

. In this declaration, add the following XML:

<init-param> <param-name>javax.faces.LIFECYCLE_ID</param-name> <param-value>com.sun.faces.lifecycle.PARTIAL</param-value></init-param>

 

This advises the

FacesServlet

to use the Ajax life cycle instead of the standard JavaServer Faces request processing life cycle. The Ajax life cycle decorates the standard one and adds the handling necessary for Ajax. Listing 1. If you have correctly installed the NetBeans SWDP modules, you should see autocompletion in the

uri=""

entry, and you should be able to choose from the list.

Add an attribute to the

<h:form>

tag:

prependId="false"

 

This new attribute in JavaServer Faces 1.2 technology advises the JavaServer Faces runtime to not prepend any naming container IDs to your component IDs within the form. The result is that the IDs you type in the markup are the actual ones that appear in the page. This is important in reducing page size and in making it easier to address markup from JavaScript code. This is line 16 in Listing 1.

After the

<h:form prependId="false" />

add the following line:

<jsfExt:scripts />

 

This is one of two tags in the Dynamic Faces tag library, and it simply instructs the runtime to render the

<script>

h:inputText>

, add the following code:

<h:commandButton value="#{res[\'register.userIDAvailableButton\']}" actionListener="#{Register_Backing.checkUserIDAvailable}" return false;" /><h:outputText style=" {color: red}" value="#{requestScope.userIDAvailableMessage}" />

 

This is line 88 in Listing

as the last JavaScript line in the

onclick

handler.

The arguments to the

DynaFaces.fireAjaxTransaction()

function are fully explained in the Project Dynamic Faces reference materials, but let's look at what you need for this example.

The first argument is the JavaScript reference to the Document Object Model (DOM) element that originates this Ajax transaction. The second argument is a JavaScript associative array of

name: value

pairs that describe the options given to this transaction. In this case, you have three options:

execute

,

render

, and

immediate

.

The

execute

option is a comma-separated list of JSF client IDs that will be traversed during the

execute

portion of the JSF request processing life cycle. Normally in JavaServer Faces technology, the entire view is traversed during this part of the life cycle, but with Dynamic Faces, you can control what subtrees in the view are traversed. Note that each client ID named in this list, along with any children of those nodes, will be traversed. For a review of the JavaServer Faces life cycle, see the Sun Web Developer Pack Tutorial.

In this example, you want the

execute

portion of the life cycle to hit the

userid

and the

userIDAvailable

nodes. These IDs correspond to the

<h:inputText>

for the user ID and the

<h:commandButton>

for the button to check for ID availability, respectively. You want to make sure that only these nodes are traversed because you need the user ID that the user entered to be submitted, and you want the

actionListener

for the button to be executed.

The next option is

render

. Like

execute

, this option is a comma-separated list of client IDs. But unlike

execute

, this list names the subtrees to be traversed during the

render

portion of the JavaServer Faces life cycle. In this case, the value is

userIDAvailableMessage

, which is an

<h:outputText>

, as shown on line 93 of Listing 1. The

userIdAvailableMessage

component simply outputs a request-scoped attribute that is named

userIDAvailableMessage

.

The last option is

immediate: true

. This option is like the

immediate

option on JavaServer Faces components, except that it has an effect only on this particular run through the life cycle. Its operation and intent is exactly the same as in core JavaServer Faces technology. For more on the

immediate

attribute, see the book JavaServer Faces: The Complete Reference. That's it for the rendering side of the activity.

 

Listing 2 shows a

diff

, a file comparison showing the difference between two versions of the same file, of the

register.jsp

file before and after the changes that this article discusses. As you can see, the author of this article added or changed only 11 lines.

Listing 2:

diff

of Old and New

register.jsp

Files

1. <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%> 2.  <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%> 3. +<%@ taglib uri="http://java.sun.com/jsf/extensions/dynafaces" prefix="jsfExt"%> 4.  <f:view> 5.    <f:loadBundle basename="com.jsfcompref.trainer.resources.UIResources" 6.                  var="res"/> 7.  -12,7 +13,8 @@ 8.        <link href="css/vt.css" rel="stylesheet" media="screen"></link> 9.        <link rel="shortcut icon" href="images/favicon.ico"> 10.      </head> 11. -    <body><h:form> 12. +    <body><h:form prependId="false"> 13. +        <jsfExt:scripts /> 14.          <table width="100%" border="0"> 15.            <tr> 16.              <td> 17.  -81,10 +83,17 @@ 18.                  <f:verbatim>&nbsp;</f:verbatim> 19.   20.                  <h:outputLabel value="#{res[\'register.userid\']}" for="userid"/>                21. -                <h:inputText required="true" 22. +                <h:inputText required="true" autocomplete="off" 23.                               binding="#{Register_Backing.userid}"/> 24. +                <h:commandButton 25. +                  value="#{res[\'register.userIDAvailableButton\']}" 26. +                  actionListener="#{Register_Backing.checkUserIDAvailable}" 27. +                                       render: return false;" /> 29. +                <h:outputText style="{color: red}" 30. +                         value="#{requestScope.userIDAvailableMessage}" /> 31.                  <h:message for="userid" errorClass="ValidateError"/> 32. - 33. +<br /> 34.                  <h:outputLabel value="#{res[\'register.password\']}" for="password"/>                35.                  <h:inputSecret required="true" 36.                               binding="#{Register_Backing.password}" />

 

Listing 1:

actionListener="#{Register_Backing.checkUserIDAvailable}"

 

Listing 3 shows this new method. This is a plain-old JavaServer Faces

ActionListener

method. It does not do anything specifically Ajax-related, but because you are using Dynamic Faces, it will be invoked by Ajax. On line 2 of Listing 3, you get the value of the Userid field. Note that this component is bound with a JavaServer Faces component binding, as shown on line 87 of Listing 1. For more detail on component bindings, see the book JavaServer Faces: The Complete Reference.

Because you are running the full JavaServer Faces life cycle, you know that the value has been validated and converted according to any validators or converters attached to the component.

Line 3 of Listing 3 uses a class specific to the Virtual Trainer application,

UserRegistry

, which provides a handy method,

userIdAlreadyExists

. You simply pass the user ID from the text field to this method and store a message in request scope, as shown on lines 4 through 14 of Listing 3.

Because this application is already internationalized, you will use the

ResourceBundle

for the application to get the message. Note that you are passing the current locale from the

ViewRoot

into the

ResourceBundle.getLocale()

method. This ensures that the language settings sent by the browser are correctly handled with respect to the supported localizations for this application.

Sun Web Developer Pack Tutorial. Project Dynamic Faces reference materials. Briefly, putting components within an Ajax zone causes them to be imbued with Ajax behavior such that clicking on the element will cause an Ajax transaction to the server, allowing just those components within the zone to update themselves by way of Ajax. The Sun Web Developer Pack Tutorial describes how to make action in one zone cause a reaction in another zone, all by way of Ajax. Source code for this bundle

Original source for the virtual trainer application

Download the Java EE SDK

Sun Web Developer Pack Tutorial

JavaServer Faces technology

Ajax Developer Resource Center

Ed Burns's blog

About the Author

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 支持向量机非线性回归通用MATLAB程序解析 #### 一、概述 本文将详细介绍一个基于MATLAB的支持向量机(SVM)非线性回归的通用程序。该程序采用支持向量机方法来实现数据的非线性回归,并通过不同的核函数设置来适应不同类型的数据分布。此外,该程序还提供了数据预处理的方法,使得用户能够更加方便地应用此程序解决实际问题。 #### 二、核心功能与原理 ##### 1. 支持向量机(SVM) 支持向量机是一种监督学习模型,主要用于分类和回归分析。对于非线性回归任务,SVM通过引入核技巧(kernel trick)将原始低维空间中的非线性问题转换为高维空间中的线性问题,从而实现有效的非线性建模。 ##### 2. 核函数 核函数的选择直接影响到模型的性能。本程序内置了三种常用的核函数: - **线性核函数**:`K(x, y) = x'y` - **多项式核函数**:`K(x, y) = (x'y + 1)^d` - **径向基函数(RBF)**:`K(x, y) = exp(-γ|x - y|^2)` 其中RBF核函数被广泛应用于非线性问题中,因为它可以处理非常复杂的非线性关系。本程序默认使用的是RBF核函数,参数`D`用于控制高斯核函数的宽度。 ##### 3. 数据预处理 虽然程序本身没有直接涉及数据预处理的过程,但在实际应用中,对数据进行适当的预处理是非常重要的。常见的预处理步骤包括归一化、缺失值处理等。 ##### 4. 模型参数 - **Epsilon**: ε-insensitive loss function的ε值,控制回归带宽。 - **C**: 松弛变量的惩罚系数,控制模型复杂度与过拟合的风险之间的平衡。 #### 三、程序实现细节 ##### 1. 函数输入与输出 - **输入**: - `X`: 输入特征矩阵,维度为(n, l),其中n是特征数量,l是样本数量。 - `Y`: 目标值向量,长度为l。 - `Epsilon`: 回归带宽。 - `C`: 松弛变量的惩罚系数。 - `D`: RBF核函数的参数。 - **输出**: - `Alpha1`: 正的拉格朗日乘子向量。 - `Alpha2`: 负的拉格朗日乘子向量。 - `Alpha`: 拉格朗日乘子向量。 - `Flag`: 标记向量,表示每个样本的类型。 - `B`: 偏置项。 ##### 2. 核心代码解析 程序首先计算所有样本间的核矩阵`K`,然后构建二次规划问题并求解得到拉格朗日乘子向量。根据拉格朗日乘子的值确定支持向量,并计算偏置项`B`。 - **核矩阵计算**:采用RBF核函数,通过`exp(-(sum((xi-xj).^2)/D))`计算任意两个样本之间的相似度。 - **二次规划**:构建目标函数和约束条件,使用`quadprog`函数求解最小化问题。 - **支持向量识别**:根据拉格朗日乘子的大小判断每个样本是否为支持向量,并据此计算偏置项`B`。 #### 四、程序扩展与优化 - **多核函数支持**:可以通过增加更多的核函数选项,提高程序的灵活性。 - **自动调参**:实现参数自动选择的功能,例如通过交叉验证选择最优的`Epsilon`和`C`值。 - **并行计算**:利用MATLAB的并行计算工具箱加速计算过程,特别是当样本量很大时。 #### 五、应用场景 该程序适用于需要进行非线性回归预测的场景,如经济预测、天气预报等领域。通过调整核函数和参数,可以有效应对各种类型的非线性问题。 ### 总结 本程序提供了一个支持向量机非线性回归的完整实现框架,通过灵活的核函数设置和参数调整,能够有效地处理非线性问题。对于需要进行回归预测的应用场景,这是一个非常实用且强大的工具。
项目:JavaScript 中的 Canyon Runner 游戏 Canyon Runner Game 是一个 HTML5 和 JavaScript 项目。这款游戏看起来很棒,玩起来很有趣。这款游戏使用了 Phaser框架。如果你想编写一个简单的游戏,那么这款射击游戏就是你必玩的游戏。这款游戏包含大量 JavaScript,用于对游戏的某些部分进行验证。 游戏玩法 要运行此游戏,您不需要任何类型的本地服务器,但需要 浏览器。您可以使用 Google Chrome 或 Mozilla Firefox 获得更好、更优化的游戏体验。要先玩游戏,请在浏览 器中单击 index.html 文件打开游戏。打开后,将出现一个带有开始菜单选项的屏幕。游戏的控制是箭头键和空格键,用于射击障碍物。游戏有一个主要的太空敌人和一个健康强化。具有惊人的视差效果、复古声音等。 这款游戏的射击是自动的。当你开始游戏时,射手开始发射火箭。记住这是一款两级或两章的游戏。第一级处理障碍和障碍。你需要越过这些障碍,不要让它们碰到你。即使它们碰到你,你也可以通过吃健康能量来恢复你的健康。你可以跑得更快,也可以控制你的宇宙飞船速度。 当你通过第一关后,你将在第二章中面对主要敌人。他会不断向你发射火箭导弹。你必须躲避它们并保护自己。你可以用火箭导弹攻击敌人来杀死他们。如果你能杀死敌人,你就赢了游戏。 这款游戏玩起来很有趣,重制它更是有趣。所以希望你能给这款游戏添加一些额外的关卡。 要查看我们的项目,您可以查看下面的图像滑块。我们建议您使用 Google Chrome 以获得更好的游戏性能。 演示: 该项目为国外大神项目,可以作为毕业设计的项目,也可以作为大作业项目,不用担心代码重复,设计重复等,如果需要对项目进行修改,需要具备一定基础知识。 注意:如果装有360等杀毒软件,可能会出现误报的情况,源码本身并无病毒,使用源码时可以关闭360,或者添加信任。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值