Java学习者论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

手机号码,快捷登录

恭喜Java学习者论坛(https://www.javaxxz.com)已经为数万Java学习者服务超过8年了!积累会员资料超过10000G+
成为本站VIP会员,下载本站10000G+会员资源,购买链接:点击进入购买VIP会员
JAVA高级面试进阶视频教程Java架构师系统进阶VIP课程

分布式高可用全栈开发微服务教程

Go语言视频零基础入门到精通

Java架构师3期(课件+源码)

Java开发全终端实战租房项目视频教程

SpringBoot2.X入门到高级使用教程

大数据培训第六期全套视频教程

深度学习(CNN RNN GAN)算法原理

Java亿级流量电商系统视频教程

互联网架构师视频教程

年薪50万Spark2.0从入门到精通

年薪50万!人工智能学习路线教程

年薪50万!大数据从入门到精通学习路线年薪50万!机器学习入门到精通视频教程
仿小米商城类app和小程序视频教程深度学习数据分析基础到实战最新黑马javaEE2.1就业课程从 0到JVM实战高手教程 MySQL入门到精通教程
查看: 381|回复: 0

[jsf学习]jsf标准实例猜数字

[复制链接]
  • TA的每日心情
    开心
    2021-3-12 23:18
  • 签到天数: 2 天

    [LV.1]初来乍到

    发表于 2014-10-10 03:55:54 | 显示全部楼层 |阅读模式
    从下载的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. 我想好了一个数字,范围是
    <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>
         数字的最大值、最小值、猜对与否、及数字的验证都绑到了UserNumberBean上,没有使用标准验证器。且来看看这个应用中的主角:

    1. package guessNumber;
    2. import javax.faces.component.UIComponent;
    3. import javax.faces.context.FacesContext;
    4. import javax.faces.validator.LongRangeValidator;
    5. import javax.faces.validator.Validator;
    6. import javax.faces.validator.ValidatorException;
    7. import java.util.Random;
    8. public class UserNumberBean {
    9.     Integer userNumber = null;
    10.     Integer randomInt = null;
    11.     String  response = null;
    12.     protected String[] status = null;
    13.     private int minimum = 0;
    14.     private boolean minimumSet = false;
    15.     private int maximum = 0;
    16.     private boolean maximumSet = false;
    17.     public UserNumberBean() {
    18.         Random randomGR = new Random();
    19.         randomInt = new Integer(randomGR.nextInt(10));
    20.         System.out.println("Duke"s number: " + randomInt);
    21.     }
    22.     public void setUserNumber(Integer user_number) {
    23.         userNumber = user_number;
    24.         System.out.println("Set userNumber " + userNumber);
    25.     }
    26.     public Integer getUserNumber() {
    27.         System.out.println("get userNumber " + userNumber);
    28.         return userNumber;
    29.     }
    30.     public String getResponse() {
    31.         if (userNumber != null && userNumber.compareTo(randomInt) == 0) {
    32.             return "Yay! You got it!";
    33.         } else {
    34.             return "Sorry, " + userNumber + " is incorrect.";
    35.         }
    36.     }
    37.   
    38.     public String[] getStatus() {
    39.         return status;
    40.     }
    41.     public void setStatus(String[] newStatus) {
    42.         status = newStatus;
    43.     }
    44.    
    45.     public int getMaximum() {
    46.         return (this.maximum);
    47.     }
    48.     public void setMaximum(int maximum) {
    49.         this.maximum = maximum;
    50.         this.maximumSet = true;
    51.     }
    52.     public int getMinimum() {
    53.         return (this.minimum);
    54.     }
    55.     public void setMinimum(int minimum) {
    56.         this.minimum = minimum;
    57.         this.minimumSet = true;
    58.     }
    59.     public void validate(FacesContext context,
    60.                          UIComponent component,
    61.                          Object value) throws ValidatorException {
    62.         if ((context == null) || (component == null)) {
    63.             throw new NullPointerException();
    64.         }
    65.         if (value != null) {
    66.             try {
    67.                 int converted = intValue(value);
    68.                 if (maximumSet &&
    69.                     (converted > maximum)) {
    70.                     if (minimumSet) {
    71.                         throw new ValidatorException(
    72.                             MessageFactory.getMessage
    73.                             (context,
    74.                              Validator.NOT_IN_RANGE_MESSAGE_ID,
    75.                              new Object[]{
    76.                                  new Integer(minimum),
    77.                                  new Integer(maximum)
    78.                              }));
    79.                     } else {
    80.                         throw new ValidatorException(
    81.                             MessageFactory.getMessage
    82.                             (context,
    83.                              LongRangeValidator.MAXIMUM_MESSAGE_ID,
    84.                              new Object[]{
    85.                                  new Integer(maximum)
    86.                              }));
    87.                     }
    88.                 }
    89.                 if (minimumSet &&
    90.                     (converted < minimum)) {
    91.                     if (maximumSet) {
    92.                         throw new ValidatorException(MessageFactory.getMessage
    93.                                                      (context,
    94.                                                       Validator.NOT_IN_RANGE_MESSAGE_ID,
    95.                                                       new Object[]{
    96.                                                           new Double(minimum),
    97.                                                           new Double(maximum)
    98.                                                       }));
    99.                     } else {
    100.                         throw new ValidatorException(
    101.                             MessageFactory.getMessage
    102.                             (context,
    103.                              LongRangeValidator.MINIMUM_MESSAGE_ID,
    104.                              new Object[]{
    105.                                  new Integer(minimum)
    106.                              }));
    107.                     }
    108.                 }
    109.              } catch (NumberFormatException e) {
    110.                 throw new ValidatorException(
    111.                     MessageFactory.getMessage
    112.                     (context, LongRangeValidator.TYPE_MESSAGE_ID));
    113.             }
    114.         }
    115.     }
    116.     private int intValue(Object attributeValue)
    117.         throws NumberFormatException {
    118.         if (attributeValue instanceof Number) {
    119.             return (((Number) attributeValue).intValue());
    120.         } else {
    121.             return (Integer.parseInt(attributeValue.toString()));
    122.         }
    123.     }
    124. }
    125.      数字的最小值,最大值在faces-config.xml中设置。这里主要看看那个validate方法,它在数字不在0-10范围时,
    126. 抛出ValidatorException异常。异常信息将会由标记<h:message for="userNo">输出。这些异常信息如何本地化定制?
    127. 那就是从资源包中获取!请看:
    复制代码

    1. package guessNumber;
    2. import javax.faces.application.Application;
    3. import javax.faces.application.FacesMessage;
    4. import javax.faces.context.FacesContext;
    5. import java.text.MessageFormat;
    6. import java.util.Locale;
    7. import java.util.MissingResourceException;
    8. import java.util.ResourceBundle;
    9. public class MessageFactory extends Object {
    10.    
    11.     private MessageFactory() {
    12.     }
    13.    //这个方法是用做参数替换
    14.    
    15.     public static String substituteParams(Locale locale, String msgtext, Object params[]) {
    16.         String localizedStr = null;
    17.         if (params == null || msgtext == null) {
    18.             return msgtext;
    19.         }
    20.         StringBuffer b = new StringBuffer(100);
    21.         MessageFormat mf = new MessageFormat(msgtext);
    22.         if (locale != null) {
    23.             mf.setLocale(locale);
    24.             b.append(mf.format(params));
    25.             localizedStr = b.toString();
    26.         }
    27.         return localizedStr;
    28.     }

    29. //上面方法的用法例子
    30.     public static void main(String args[]){
    31.          String msgtext="我由于{0},不能去{1}";
    32.          String params[]={"有事","北京"};
    33.          String s=substituteParams(Locale.CHINESE,msgtext,params);
    34.          System.out.println(s);
    35.    }
    36. /**
    37. 运行结果:
    38.   D:java>java   Test
    39.   我由于有事,不能去北京
    复制代码
       D:java>
    */

    1.     /**
    2.      * This version of getMessage() is used in the RI for localizing RI
    3.      * specific messages.
    4.      */
    5.     public static FacesMessage getMessage(String messageId, Object params[]) {
    6.         Locale locale = null;
    7.         FacesContext context = FacesContext.getCurrentInstance();
    8.         // context.getViewRoot() may not have been initialized at this point.
    9.         if (context != null && context.getViewRoot() != null) {
    10.             locale = context.getViewRoot().getLocale();
    11.             if (locale == null) {
    12.                 locale = Locale.getDefault();
    13.             }
    14.         } else {
    15.             locale = Locale.getDefault();
    16.         }
    17.         return getMessage(locale, messageId, params);
    18.     }
    19. //从资源包中获取信息,从而构造jsf页面标记<h:message>与<h:messages>中所要显示的详细和摘要信息
    20.     public static FacesMessage getMessage(Locale locale, String messageId,
    21.                                           Object params[]) {
    22.         FacesMessage result = null;
    23.         String
    24.             summary = null,
    25.             detail = null,
    26.             bundleName = null;
    27.         ResourceBundle bundle = null;
    28.         // see if we have a user-provided bundle
    29.         if (null != (bundleName = getApplication().getMessageBundle())) {//资源包的名字
    30.             if (null !=
    31.                 (bundle =
    32.                 ResourceBundle.getBundle(bundleName, locale,
    33.                                          getCurrentLoader(bundleName)))) {//获取资源包
    34.                 // see if we have a hit
    35.                 try {
    36.                     summary = bundle.getString(messageId);//从资源包中获取信息摘要
    37.                 } catch (MissingResourceException e) {
    38.                 }
    39.             }
    40.         }
    41.         // 如果不能在用户提供的资源包中获取信息摘要,再从默认的资源包中查找
    42.         if (null == summary) {
    43.             // see if we have a summary in the app provided bundle
    44.             bundle = ResourceBundle.getBundle(FacesMessage.FACES_MESSAGES,
    45.                                               locale,
    46.                                               getCurrentLoader(bundleName));
    47.             if (null == bundle) {
    48.                 throw new NullPointerException(" bundle " + bundle);
    49.             }
    50.             // see if we have a hit
    51.             try {
    52.                 summary = bundle.getString(messageId);
    53.             } catch (MissingResourceException e) {
    54.             }
    55.         }
    56.         // we couldn"t find a summary anywhere!  Return null
    57.         if (null == summary) {
    58.             return null;
    59.         }
    60.         // At this point, we have a summary and a bundle.
    61.         if (null == summary || null == bundle) {
    62.             throw new NullPointerException(" summary " + summary + " bundle " +
    63.                 bundle);
    64.         }
    65.                 //参数替换,用参数params替换摘要中的{0},{1}等占位符。
    66.         summary = substituteParams(locale, summary, params);
    67.         try {
    68.                 //详细信息
    69.             detail = substituteParams(locale,
    70.                                       bundle.getString(messageId + "_detail"),
    71.                                       params);
    72.         } catch (MissingResourceException e) {
    73.         }
    74.         return (new FacesMessage(summary, detail));
    75.     }
    76.     //
    77.     // Methods from MessageFactory
    78.     //
    79.     public static FacesMessage getMessage(FacesContext context, String messageId) {
    80.         return getMessage(context, messageId, null);
    81.     }
    82.     public static FacesMessage getMessage(FacesContext context, String messageId,
    83.                                           Object params[]) {
    84.         if (context == null || messageId == null) {
    85.             throw new NullPointerException(" context " + context + " messageId " +
    86.                 messageId);
    87.         }
    88.         Locale locale = null;
    89.         // viewRoot may not have been initialized at this point.
    90.         if (context != null && context.getViewRoot() != null) {
    91.             locale = context.getViewRoot().getLocale();
    92.         } else {
    93.             locale = Locale.getDefault();
    94.         }
    95.         if (null == locale) {
    96.             throw new NullPointerException(" locale " + locale);
    97.         }
    98.         FacesMessage message = getMessage(locale, messageId, params);
    99.         if (message != null) {
    100.             return message;
    101.         }
    102.         locale = Locale.getDefault();
    103.         return (getMessage(locale, messageId, params));
    104.     }
    105.     public static FacesMessage getMessage(FacesContext context, String messageId,
    106.                                           Object param0) {
    107.         return getMessage(context, messageId, new Object[]{param0});
    108.     }
    109.     public static FacesMessage getMessage(FacesContext context, String messageId,
    110.                                           Object param0, Object param1) {
    111.         return getMessage(context, messageId, new Object[]{param0, param1});
    112.     }
    113.     public static FacesMessage getMessage(FacesContext context, String messageId,
    114.                                           Object param0, Object param1,
    115.                                           Object param2) {
    116.         return getMessage(context, messageId,
    117.                           new Object[]{param0, param1, param2});
    118.     }
    119.     public static FacesMessage getMessage(FacesContext context, String messageId,
    120.                                           Object param0, Object param1,
    121.                                           Object param2, Object param3) {
    122.         return getMessage(context, messageId,
    123.                           new Object[]{param0, param1, param2, param3});
    124.     }
    125.     protected static Application getApplication() {
    126.         return (FacesContext.getCurrentInstance().getApplication());
    127.     }
    128.     //获取当前的类加载器,需要该类加载器来查找资源包
    129.     protected static ClassLoader getCurrentLoader(Object fallbackClass) {
    130.         ClassLoader loader =
    131.             Thread.currentThread().getContextClassLoader();
    132.         if (loader == null) {
    133.             loader = fallbackClass.getClass().getClassLoader();
    134.         }
    135.         return loader;
    136.     }
    137. } // 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=验证错误: 数字应该在{0}和{1}之间
    javax.faces.validator.LongRangeValidator.MAXIMUM=验证错误: 数字不应该比{0}大
    javax.faces.validator.LongRangeValidator.MINIMUM=验证错误:数字不应该比{0}小
    javax.faces.validator.LongRangeValidator.TYPE=验证错误:数字类型错误.
    javax.faces.component.UIInput.CONVERSION=转换数字时发生错误.
    javax.faces.component.UIInput.REQUIRED=请输入数字 ...  

      
      
       
       

         
       

         
       
      
      

    源码下载:http://file.javaxxz.com/2014/10/10/035552875.zip
    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    QQ|手机版|Java学习者论坛 ( 声明:本站资料整理自互联网,用于Java学习者交流学习使用,对资料版权不负任何法律责任,若有侵权请及时联系客服屏蔽删除 )

    GMT+8, 2024-5-17 10:43 , Processed in 0.375247 second(s), 48 queries .

    Powered by Discuz! X3.4

    © 2001-2017 Comsenz Inc.

    快速回复 返回顶部 返回列表