JWorld@TW the best professional Java site in Taiwan
      註冊 | 登入 | 全文檢索 | 排行榜  

» JWorld@TW » Web Framework » JSF  

按列印兼容模式列印這個話題 列印話題    把這個話題寄給朋友 寄給朋友    訂閱主題
reply to topicthreaded modego to previous topicgo to next topic
己加入精華區
by browser at 2007-04-18 18:21
本主題所含的標籤
無標籤
作者 使用Ajax(4jsf)驗證資料 [精華]
holicy





發文: 14
積分: 2
於 2007-04-18 17:25 user profilesend a private message to userreply to postreply to postsearch all posts byselect and copy to clipboard. 
ie only, sorry for netscape users:-)add this post to my favorite list
JavaServer Faces雖然已提供了(伺服器端)資料驗證(Validation)的機制,
但如果每次驗證都需要重新讀取頁面,感覺既沒有效率,操作起來也不方便。
Ajax能解決這個問題,但要如何應用在JSF技術上呢?

Ajax4jsf應該是可行的答案之一,可惜用Google找不到什麼文件和參考範例。
後來我在JBoss網頁上其中一個Ajax4jsf demo,a4j-numberguess-facelets,
發現了使用Ajax4jsf驗證資料的方法。

我自己也寫了一個簡單範例,讓大家參考!

未使用Ajax4jsf的範例:
1
2
3
4
5
6
7
8
9
10
11
<f:view>
  <h:form>
    <h3>Please input something:</h3>
    <h:inputText id="msg-in" value="#{echoBean.message}" validator="#{echoBean.validate}" />
    <h:message for="msg-in" showSummary="true" showDetail="false"
        style="margin-left:.2em; color:red; font-size:.9em" />
    <h3>
      Echo: <h:outputText id="msg" value="#{echoBean.message}" />
    </h3>
  </h:form>
</f:view>

加入Ajax4jsf功能後的範例:
1
2
3
4
5
6
7
8
9
10
11
12
13
<f:view>
  <a4j:form ajaxSubmit="true" reRender="msg">
    <h3>Please input something:</h3>
    <h:inputText id="msg-in" value="#{echoBean.message}" validator="#{echoBean.validate}" />
    <a4j:outputPanel ajaxRendered="true">
      <h:message for="msg-in" showSummary="true" showDetail="false"
          style="margin-left:.2em; color:red; font-size:.9em" />
    </a4j:outputPanel>
    <h3>
      Echo: <h:outputText id="msg" value="#{echoBean.message}" />
    </h3>
  </a4j:form>
</f:view>

基本上就是替換原本的h:form成為a4j:form,並設定屬性ajaxSubmit為true,
範例還設定了reRender屬性,此為指定當在輸入欄中按下Enter時,欲動態更新的輸出元件。
另外為了讓驗證訊息也能動態更新,使用a4j:outputPanel把h:message包起來,
並設定屬性ajaxRendered為true。

順便附上Bean的原始檔

EchoBean.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package org.demo;
 
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.ValidatorException;
 
public class EchoBean {
 
  private String message;
  
  public EchoBean() {}
  
  public void setMessage( String message )
  {
    this.message = message;
  }
  
  public String getMessage()
  {
    return message;
  }
  
  public void validate( FacesContext context, UIComponent component, Object value )
  throws ValidatorException
  {
    if( !value.toString().matches( "\\w*" ) ) {
      FacesMessage msg = new FacesMessage( "must match regex: \\w*" );
      throw new ValidatorException( msg );
    }
  }
  
}

其它部份,如設定檔web.xml與faces-config.xml等,在此省略不提。

* * *
Ajax4jsf Online Demos:
http://labs.jboss.com/portal/jbossajax4jsf/demo/index.html

Ajax4jsf Developer Guide:
http://labs.jboss.com/file-access/default/members/jbossajax4jsf/freezone/docs/devguide/index.html


holicy edited on 2007-04-18 19:27
reply to postreply to post
作者 Re:使用Ajax(4jsf)驗證資料 [Re:holicy]
kcleung





發文: 19
積分: 0
於 2007-06-04 01:37 user profilesend a private message to userreply to postreply to postsearch all posts byselect and copy to clipboard. 
ie only, sorry for netscape users:-)add this post to my favorite list
根據你提供的範例,我寫了一個用戶登入 / 登出的例子,
首先會顯示 loginForm,如果登入成功,loginForm 便會消失,
切換為 logoutForm,在 logoutForm 按 1 下 Logout,
用戶便會登出,從新顯示 loginForm。
過程以 AJAX 形式進行。

建立資料表為 `users`,有以下欄位 :

name ( Text )
password ( Text )
nickname ( Text )

設定好 JDBC DataSources
http://tomcat.apache.org/tomcat-5.5-doc/jndi-datasource-examples-howto.html

假設 Data Source 的名稱為 "jdbc/localhost"。

新增 1 個 Java 類別 users.UserBean 如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package users;
 
import java.sql.*;
 
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
 
public class UserBean {
  private String nickname = "" ;
  private String name = "" ;
  private String password = "" ;
 
  // 登入狀態
  private boolean login = false ;
 
  /* setter, getter ... 省略。*/
 
  /*
  登出,把所有屬性設為空值,
  把登入狀態設為未登入。
  */
  public void logout() {
    name = "" ;
    password = "" ;
    nickname = "" ;
    login = false ;
  }
 
  // 登入
  private void login(String name, String password)
    throws NamingException, SQLException {
    logout();  // 先登出一次
 
    // 建立 DataSource, Connection, Statement ... 省略。
 
    String sql = "SELECT * FROM `users` WHERE `name` = '"
      + name + "' AND `password` = PASSWORD('" + password + "') ;";
 
    ResultSet resultSet = statement.executeQuery(sql);
 
    /* 如果 resultSet.next ( ) 為 true
    即是 name 與 password 正確
    */
    if (resultSet.next()) {
      this.name = resultSet.getString("name");
      nickname = resultSet.getString("nickname");
      this.password = password;
      login = true;
    }
    // 當登入失敗,把訊息送出
    else {
      FacesContext facesContext = FacesContext.getCurrentInstance();
      FacesMessage facesMessage = new FacesMessage();
      facesMessage.setSeverity(FacesMessage.SEVERITY_ERROR);
      facesMessage.setSummary("Login error.");
      facesMessage.setDetail("Incorrect username or password.");
      facesContext.addMessage("loginForm", facesMessage);
 
    }
  }
}


設定 UserBean:
1
2
3
4
5
<managed-bean>
  <managed-bean-name>user</managed-bean-name>
  <managed-bean-class>users.UserBean</managed-bean-class>
  <managed-bean-scope>session</managed-bean-scope>
</managed-bean>


/users/login/index.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<?xml version="1.0" encoding="UTF-8" ?>
<jsp:root xmlns:a4j="https://ajax4jsf.dev.java.net/ajax"
  xmlns:f="http://java.sun.com/jsf/core"
  xmlns:h="http://java.sun.com/jsf/html"
  xmlns:jsp="http://java.sun.com/JSP/Page" version="2.0">
  <jsp:directive.page language="java"
    contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" />
  <jsp:text>
    <![CDATA[ <?xml version="1.0" encoding="UTF-8" ?> ]]>
  </jsp:text>
  <jsp:text>
    <![CDATA[ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> ]]>
  </jsp:text>
  <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US"
    lang="en-US">
  <head profile="http://www.w3.org/2000/08/w3c-synd/#">
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <title>Main -> Users -> Login</title>
  </head>
  <body>
  <f:view>
    <a4j:outputPanel ajaxRendered="true">
      <a4j:form id="loginForm" ajaxSubmit="true" rendered="#{!user.login}">
        <h:panelGrid columns="2">
          <h:outputText value="Username:" />
          <h:inputText id="name" value="#{user.name}" required="true">
            <f:validateLength maximum="20" minimum="6" />
          </h:inputText>
          <h:outputText value="Password:" />
          <h:inputSecret id="password" value="#{user.password}"
            required="true">
            <f:validateLength minimum="6" />
          </h:inputSecret>
          <a4j:commandButton type="submit" action="#{user.login}"
            value="Login" />
        </h:panelGrid>
      </a4j:form>
      <h:messages showDetail="true" showSummary="false" />
    </a4j:outputPanel>
    <a4j:outputPanel ajaxRendered="true">
      <a4j:form id="logoutForm" ajaxSubmit="true" rendered="#{user.login}">
        <a4j:commandButton type="submit" action="#{user.logout}"
          value="Logout" />
      </a4j:form>
    </a4j:outputPanel>
  </f:view>
  </body>
  </html>
</jsp:root>


reply to postreply to post
» JWorld@TW »  Web Framework » JSF

reply to topicthreaded modego to previous topicgo to next topic
  已讀文章
  新的文章
  被刪除的文章
Jump to the top of page

JWorld@TW 本站商標資訊

Powered by Powerful JuteForum® Version Jute 1.5.8