JSF 2.0 + Ajax hello world example

In JSF 2.0, coding Ajax is just like coding a normal HTML tag, it’s extremely easy. In this tutorial, you will restructure the last JSF 2.0 hello world example, so that, when the button is clicked, it will make an Ajax request instead of submitting the whole form.

1. JSF 2.0 Page

A JSF 2.0 xhtml page with Ajax support.

helloAjax.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:f="http://java.sun.com/jsf/core"      
      xmlns:h="http://java.sun.com/jsf/html">

    <h:body>
        <div><div class="ads-in-post hide_if_width_less_800">
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- 728x90 - After1stH4 -->
<ins class="adsbygoogle hide_if_width_less_800" 
     style="display:inline-block;width:728px;height:90px"
     data-ad-client="ca-pub-2836379775501347"
     data-ad-slot="7391621200"
     data-ad-region="mkyongregion"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div></div><h2>JSF 2.0 + Ajax Hello World Example</h2>

        <h:form>
           <h:inputText id="name" value="#{helloBean.name}"></h:inputText>
           <h:commandButton value="Welcome Me">
             <f:ajax execute="name" render="output" />
           </h:commandButton>

           <div><div class="ads-in-post hide_if_width_less_800">
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- 728x90 - After2ndH4 -->
<ins class="adsbygoogle hide_if_width_less_800" 
     style="display:inline-block;width:728px;height:90px"
     data-ad-client="ca-pub-2836379775501347"
     data-ad-slot="3642936086"
     data-ad-region="mkyongregion"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div></div><h2><h:outputText id="output" value="#{helloBean.sayWelcome}" /></h2>   
        </h:form>

    </h:body>
</html>

In this example, it make the button Ajaxable. When the button is clicked, it will make an Ajax request to the server instead of submitting the whole form.

<h:commandButton value="Welcome Me">
    <f:ajax execute="name" render="output" />
</h:commandButton>
<h:outputText id="output" value="#{helloBean.sayWelcome}" />

In the <f:ajax> tag :

  • execute=”name” – Indicate the form component with an Id of “name” will be sent to the server for processing. For multiple components, just split it with a space in between, e.g execute=”name anotherId anotherxxId”. In this case, it will submit the text box value.
  • render=”output” – After the Ajax request, it will refresh the component with an id of “output“. In this case, after the Ajax request is finished, it will refresh the <h:outputText> component.

2. ManagedBean

See the full #{helloBean} example.

HelloBean.java

package com.mkyong.common;

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

import java.io.Serializable;

@ManagedBean
@SessionScoped
public class HelloBean implements Serializable {

    private static final long serialVersionUID = 1L;

    private String name;

    public String getName() {
       return name;
    }
    public void setName(String name) {
       this.name = name;
    }
    public String getSayWelcome(){
       //check if null?
       if("".equals(name) || name ==null){
        return "";
       }else{
        return "Ajax message : Welcome " + name;
       }
    }
}

3. How it work?

Access the URL : http://localhost:8080/JavaServerFaces/helloAjax.jsf
jsf2-ajax-hello-world-example-1

When the button is clicked, it makes an Ajax request and pass the text box value to the server for processing. After that, it refresh the outputText component and display the value via getSayWelcome() method, without any “page flipping effect“.
jsf2-ajax-hello-world-example-2

Ajax请求session超时处理流程 java服务器端处理: SessionValidateFilter中修改: if (ServerInfo.isAjax(request)) { request.setAttribute("statusCode", 301); request.setAttribute("message", "Session timeout!"); response.sendRedirect(response.encodeRedirectURL("/ajaxDone.jsp"); else { response.sendRedirect(response.encodeRedirectURL(this.loginUrl + java.net.URLEncoder.encode(backToUrl, "UTF-8"))); } ajaxDone.jsp页面 <%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%> { statusCode:${statusCode}, message:"${message}", objectId:"${objectId}" } js客户端处理: ajax load页面碎片处理: 自己写一个loadUrl()方法,不能使用jquery自带的load(). 当客户端调用loadUrl()超时,弹出一个登录框,并加一个背景层下面的整个浏览器.这时浏览器窗口内容不能变,只是上面加了一个登录框和一个背景层 当用户输入username and password登录成功后,去掉登录框和背景层.这时用户可以继续操作. 登录失败alert出错信息,浏览器窗口内容还是不变. var DWZ = { loginUrl:"/render.do?method=login", ajaxDoneEval:function (json) { //session timeout try{ return eval('(' + json + ')'); } catch (e){ return {}; } } }; (function($){ $.extend({ loadUrl: function(url,data,callback){ var aData = data || {}; aData["timestamp"] = new Date().getTime(); var $this = $(this); $.get(url, aData, function(data){ var json = DWZ.ajaxDoneEval(data); if (json.statusCode==301){ alertMsg.error(json.message, {okCall:function(){ window.location = "/render.do?method=login"; //popLoginWin(); }}); } else { $this.html(data).initUI(); if (jQuery.isFunction(callback)) callback(); } }); } }); })(jQuery); ajax post 表单数据处理: 当客户端ajax提交表单超时, 弹出一个登录框,并加一个背景层下面的整个浏览器. 当用户输入username and password登录成功后,去掉登录框和背景层.这时用户可以继续操作. 登录失败alert出错信息. $.post(form.action, params, callback(json){ if (json.statusCode == 301) { //301 状态表示 session timeout popLoginWin(); }else if (json.statusCode == 300) { //300 状态表示 操作失败 alertMsg.error(json.message); } else if(json.statusCode == 200) { //300 状态表示 操作成功 alertMsg.correct(json.message); } }, "json");
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值