posts - 1, comments - 1, trackbacks - 0, articles - 13
            BlogJava :: 首頁 :: 新隨筆 :: 聯(lián)系 :: 聚合  :: 管理

          jsf簡單例子

          Posted on 2007-06-06 17:27 Linden.zhang 閱讀(680) 評論(0)  編輯  收藏 所屬分類: Jsf
          從下載的jsf-1_1_01中看到了四個例子,(下載地址:  http://java.sun.com/j2ee/javaserverfaces/download.html),自己jsf剛剛起步,應該認真研究。
             首先下載jsf-1_1_01.zip,并解壓。在解壓的目錄中找到samples目錄,把其中的jsf-cardemo.war放到Tomcat  5的webapps目錄中,啟動Tomcat  5,在瀏覽器中輸入:http://127.0.0.1:8080/jsf-guessNumber/。




                 
          例子是簡單了點!
          greeting.jsp

          程序代碼:
          <%@ page contentType="text/html;charset=GBK"%> 
          <HTML>
          <HEAD> <title>Hello</title> </HEAD>
          <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
          <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
          <body bgcolor="white">
          <f:view>
          <h:form id="helloForm" >
          <h2>我的名字叫Duke. 我想好了一個數(shù)字,范圍是
          <h:outputText value="#{UserNumberBean.minimum}"/> 到
          <h:outputText value="#{UserNumberBean.maximum}"/>. 你能猜出它?
          </h2>   


          <h:graphicImage id="waveImg" url="/wave.med.gif" />
          <h:inputText id="userNo" value="#{UserNumberBean.userNumber}"    validator="#{UserNumberBean.validate}"/> 
          <h:commandButton id="submit" action="success" value="Submit" />
          <p>
          <h:message style="color: red; font-family: 'new Century Schoolbook', serif; font-style: oblique; text-decoration: overline" id="errors1" for="userNo"/>

          </h:form>
          </f:view>
          </body>
          </HTML> 


                 數(shù)字的最大值、最小值、猜對與否、及數(shù)字的驗證都綁到了UserNumberBean上,沒有使用標準驗證器。且來看看這個應用中的主角:  

          程序代碼:
          package guessNumber;
          import javax.faces.component.UIComponent;
          import javax.faces.context.FacesContext;
          import javax.faces.validator.LongRangeValidator;
          import javax.faces.validator.Validator;
          import javax.faces.validator.ValidatorException;
          import java.util.Random;
          public class UserNumberBean {
              Integer userNumber = null;
              Integer randomint null;
              String  response = null;
              protected String[] status = null;
              private int minimum = 0;
              private boolean minimumSet = false;
              private int maximum = 0;
              private boolean maximumSet = false;
              public UserNumberBean() {
                  Random randomGR = new Random();
                  randomint new Integer(randomGR.nextInt(10));
                  System.out.println("Duke's number: " + randomInt);
              }
              public void setUserNumber(Integer user_number) {
                  userNumber = user_number;
                  System.out.println("Set userNumber " + userNumber);
              }
              public Integer getUserNumber() {
                  System.out.println("get userNumber " + userNumber);
                  return userNumber;
              }
              public String getResponse() {
                  if (userNumber != null && userNumber.compareTo(randomInt) == 0) {
                      return "Yay! You got it!";
                  } else {
                      return "Sorry, " + userNumber + " is incorrect.";
                  }
              }
            
              public String[] getStatus() {
                  return status;
              }
              public void setStatus(String[] newStatus) {
                  status = newStatus;
              }
             
              public int getMaximum() {
                  return (this.maximum);
              }
              public void setMaximum(int maximum) {
                  this.maximum = maximum;
                  this.maximumSet = true;
              }
              public int getMinimum() {
                  return (this.minimum);
              }
              public void setMinimum(int minimum) {
                  this.minimum = minimum;
                  this.minimumSet = true;
              }
              public void validate(FacesContext context,
                                   UIComponent component,
                                   Object value) throws ValidatorException {
                  if ((context == null) || (component == null)) {
                      throw new nullPointerException();
                  }
                  if (value != null) {
                      try {
                          int converted = intValue(value);
                          if (maximumSet &&
                              (converted > maximum)) {
                              if (minimumSet) {
                                  throw new ValidatorException(
                                      MessageFactory.getMessage
                                      (context,
                                       Validator.NOT_IN_RANGE_MESSAGE_ID,
                                       new Object[]{
                                           new Integer(minimum),
                                           new Integer(maximum)
                                       }));
                              } else {
                                  throw new ValidatorException(
                                      MessageFactory.getMessage
                                      (context,
                                       LongRangeValidator.MAXIMUM_MESSAGE_ID,
                                       new Object[]{
                                           new Integer(maximum)
                                       }));
                              }
                          }
                          if (minimumSet &&
                              (converted < minimum)) {
                              if (maximumSet) {
                                  throw new ValidatorException(MessageFactory.getMessage
                                                               (context,
                                                                Validator.NOT_IN_RANGE_MESSAGE_ID,
                                                                new Object[]{
                                                                    new Double(minimum),
                                                                    new Double(maximum)
                                                                }));
                              } else {
                                  throw new ValidatorException(
                                      MessageFactory.getMessage
                                      (context,
                                       LongRangeValidator.MINIMUM_MESSAGE_ID,
                                       new Object[]{
                                           new Integer(minimum)
                                       }));
                              }
                          }
                       } catch (NumberFormatException e) {
                          throw new ValidatorException(
                              MessageFactory.getMessage
                              (context, LongRangeValidator.TYPE_MESSAGE_ID));
                      }
                  }
              }
              private int intValue(Object attributeValue)
                  throws NumberFormatException {
                  if (attributeValue instanceof Number) {
                      return (((Number) attributeValue).intValue());
                  } else {
                      return (Integer.parseInt(attributeValue.toString()));
                  }
              }
          }


                   數(shù)字的最小值,最大值在faces-config.xml中設置。這里主要看看那個validate方法,它在數(shù)字不在0-10范圍時,拋出ValidatorException異常。異常信息將會由標記<h:message  for="userNo">輸出。這些異常信息如何本地化定制?那就是從資源包中獲取!請看:

          程序代碼:
          package guessNumber;
          import javax.faces.application.Application;
          import javax.faces.application.FacesMessage;
          import javax.faces.context.FacesContext;
          import java.text.MessageFormat;
          import java.util.Locale;
          import java.util.MissingResourceException;
          import java.util.ResourceBundle;
          public class MessageFactory extends Object {
             
              private MessageFactory() {
              }
             //這個方法是用做參數(shù)替換
              
              public static String substituteParams(Locale locale, String msgtext, Object params[]) {
                  String localizedStr = null;
                  if (params == null || msgtext == null) {
                      return msgtext;
                  }
                  StringBuffer b = new StringBuffer(100);
                  MessageFormat mf = new MessageFormat(msgtext);
                  if (locale != null) {
                      mf.setLocale(locale);
                      b.append(mf.format(params));
                      localizedStr = b.toString();
                  }
                  return localizedStr;
              }
          //上面方法的用法例子
              public static void main(String args[]){         String msgtext="我由于{0},不能去{1}";         String params[]={"有事","北京"};         String s=substituteParams(Locale.CHINESE,msgtext,params);         System.out.println(s);   } 
          /**
           運行結果:  D:\java>java   Test  我由于有事,不能去北京
             D:\java>
          */
           

              /**
               * This version of getMessage() is used in the RI for localizing RI
               * specific messages.
               */

              public static FacesMessage getMessage(String messageId, Object params[]) {
                  Locale locale = null;
                  FacesContext context = FacesContext.getCurrentInstance();
                  // context.getViewRoot() may not have been initialized at this point.
                  if (context != null && context.getViewRoot() != null) {
                      locale = context.getViewRoot().getLocale();
                      if (locale == null) {
                          locale = Locale.getDefault();
                      }
                  } else {
                      locale = Locale.getDefault();
                  }
                  return getMessage(locale, messageId, params);
              }
          //從資源包中獲取信息,從而構造jsf頁面標記<h:message>與<h:messages>中所要顯示的詳細和摘要信息
              public static FacesMessage getMessage(Locale locale, String messageId,
                                                    Object params[]) {
                  FacesMessage result = null;
                  String
                      summary = null,
                      detail = null,
                      bundleName = null;
                  ResourceBundle bundle = null;
                  // see if we have a user-provided bundle
                  if (null != (bundleName = getApplication().getMessageBundle())) {//資源包的名字
                      if (null !=
                          (bundle =
                          ResourceBundle.getBundle(bundleName, locale,
                                                   getCurrentLoader(bundleName)))) {//獲取資源包
                          // see if we have a hit
                          try {
                              summary = bundle.getString(messageId);//從資源包中獲取信息摘要
                          } catch (MissingResourceException e) {
                          }
                      }
                  }
                  // 如果不能在用戶提供的資源包中獲取信息摘要,再從默認的資源包中查找
                  if (null == summary) {
                      // see if we have a summary in the app provided bundle
                      bundle = ResourceBundle.getBundle(FacesMessage.FACES_MESSAGES,
                                                        locale,
                                                        getCurrentLoader(bundleName));
                      if (null == bundle) {
                          throw new nullPointerException(" bundle " + bundle);
                      }
                      // see if we have a hit
                      try {
                          summary = bundle.getString(messageId);
                      } catch (MissingResourceException e) {
                      }
                  }
                  // we couldn't find a summary anywhere!  return null
                  if (null == summary) {
                      return null;
                  }
                  // At this point, we have a summary and a bundle.
                  if (null == summary || null == bundle) {
                      throw new nullPointerException(" summary " + summary + " bundle " + 
                          bundle);
                  }
          //參數(shù)替換,用參數(shù)params替換摘要中的{0},{1}等占位符。
                  summary = substituteParams(locale, summary, params);
                  try {
          //詳細信息
                      detail = substituteParams(locale,
                                                bundle.getString(messageId + "_detail"),
                                                params);
                  } catch (MissingResourceException e) {
                  }
                  return (new FacesMessage(summary, detail));
              }
              //
              // Methods from MessageFactory
              // 
              public static FacesMessage getMessage(FacesContext context, String messageId) {
                  return getMessage(context, messageId, null);
              }
              public static FacesMessage getMessage(FacesContext context, String messageId,
                                                    Object params[]) {
                  if (context == null || messageId == null) {
                      throw new nullPointerException(" context " + context + " messageId " + 
                          messageId);
                  }
                  Locale locale = null;
                  // viewRoot may not have been initialized at this point.
                  if (context != null && context.getViewRoot() != null) {
                      locale = context.getViewRoot().getLocale();
                  } else {
                      locale = Locale.getDefault();
                  }
                  if (null == locale) {
                      throw new nullPointerException(" locale " + locale);
                  }
                  FacesMessage message = getMessage(locale, messageId, params);
                  if (message != null) {
                      return message;
                  }
                  locale = Locale.getDefault();
                  return (getMessage(locale, messageId, params));
              }
              public static FacesMessage getMessage(FacesContext context, String messageId,
                                                    Object param0) {
                  return getMessage(context, messageId, new Object[]{param0});
              }
              public static FacesMessage getMessage(FacesContext context, String messageId,
                                                    Object param0, Object param1) {
                  return getMessage(context, messageId, new Object[]{param0, param1});
              }
              public static FacesMessage getMessage(FacesContext context, String messageId,
                                                    Object param0, Object param1,
                                                    Object param2) {
                  return getMessage(context, messageId,
                                    new Object[]{param0, param1, param2});
              }
              public static FacesMessage getMessage(FacesContext context, String messageId,
                                                    Object param0, Object param1,
                                                    Object param2, Object param3) {
                  return getMessage(context, messageId,
                                    new Object[]{param0, param1, param2, param3});
              }
              protected static Application getApplication() {
                  return (FacesContext.getCurrentInstance().getApplication());
              }
              //獲取當前的類加載器,需要該類加載器來查找資源包
              protected static ClassLoader getCurrentLoader(Object fallbackClass) {
                  ClassLoader loader =
                      Thread.currentThread().getContextClassLoader();
                  if (loader == null) {
                      loader = fallbackClass.getClass().getClassLoader();
                  }
                  return loader;
              }
          } // end of class MessageFactory



          當然我們需要在faces-config.xml中定義資源包名

          程序代碼:
          <application>
          <locale-config>
            <default-locale>zh_CN</default-locale>
             <supported-locale>en</supported-locale>
             <supported-locale>fr</supported-locale>
             <supported-locale>es</supported-locale>
          </locale-config>
          <message-bundle>guessNumber.messages</message-bundle>
          </application>



          并寫出messages_zh_CN.properties文件:
          javax.faces.validator.NOT_IN_RANGE=驗證錯誤:  數(shù)字應該在{0}和{1}之間
          javax.faces.validator.LongRangeValidator.MAXIMUM=驗證錯誤:  數(shù)字不應該比{0}大
          javax.faces.validator.LongRangeValidator.MINIMUM=驗證錯誤:數(shù)字不應該比{0}小  
          javax.faces.validator.LongRangeValidator.TYPE=驗證錯誤:數(shù)字類型錯誤.  
          javax.faces.component.UIInput.CONVERSION=轉換數(shù)字時發(fā)生錯誤.  
          javax.faces.component.UIInput.REQUIRED=請輸入數(shù)字  ...
          主站蜘蛛池模板: 苍山县| 略阳县| 柳州市| 上虞市| 金堂县| 东台市| 黄龙县| 辽宁省| 龙川县| 邳州市| 平武县| 盐亭县| 邵东县| 织金县| 专栏| 阿城市| 浠水县| 广饶县| 华安县| 乐清市| 河津市| 浙江省| 临江市| 西吉县| 射洪县| 阜新市| 汉阴县| 毕节市| 喀喇沁旗| 永吉县| 灵川县| 青铜峡市| 甘洛县| 淮安市| 英德市| 通渭县| 新巴尔虎右旗| 涞水县| 新干县| 衡南县| 申扎县|