|
Posted on 2007-06-06 17:27 Linden.zhang 阅读(676) 评论(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. 我想好了一个数字,范围是 <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上,没有使用标准验证器。且来看看这个应用中的主角:
程序代码: |
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())); } } } |
数字的最小值,最大值在faces-config.xml中设置。这里主要看看那个validate方法,它在数字不在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() { } //这个方法是用做参数替换 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); } //参数替换,用参数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=验证错误: 数字应该在{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=请输入数字 ...
|