JSF
(1.3)-入门-简单的导航Navigation
By www.coolhou.com 灰石
( http://blog.youkuaiyun.com/lmstone )
( LimingMail1998@yahoo.com.cn )
文档描述: JSF简介,Managed Beans,资料转换与验证,事件处理,JSF标签,自定义元素。1-6章原文来自http://www.javaworld.com.tw
|
3. 资料转换与验证
3.1. 标准转换器
3.2. 自定转换器
3.3. 标准验证器
3.4. 自定验证器
3.5. 错误信息处理
3.6. 自订转换,验证标签
1.3 简单的导航Navigation
我们现在要对第一个程序进行扩展,让它可以根据使用者输入的名称与密码是否正确,决定返回页。
1.3.1. 修改UserBean
/* * 创建日期 2005-12-27 * * 描述: * 酷猴.Java学习工程 * * MAIL: limingmail1998@yahoo.com.cn * 网址: http://www.coolhou.com * 博客: http://blog.youkuaiyun.com/lmstone * */ package com.coolhou.student.jsf.caterpillar.form;
/** * 一个简单的java类 * * @author 李明 * @version 2005-12-27 18:54:54 */ public class UserBean { private String name; private String password; private String errMessage;
public void setName(String name) { this.name = name; }
public String getName() { return name; }
public void setPassword(String password) { this.password = password; }
public String getPassword() { return password; }
public void setErrMessage(String errMessage) { this.errMessage = errMessage; }
public String getErrMessage() { return errMessage; }
public String verify() { if(!name.equals("justin") || !password.equals("123456")) { errMessage = "名称或密码错误"; return "failure"; } else { return "success"; } } } |
在verify()方法中,检查名称与密码,返回一个字串,“failure”表示登录错误,并设定错误信息,而”success”表示登录正确,返回的字串决定页面的流向。
1.3.2. 修改faces-config.xml
<?xml version="1.0" encoding="gb2312"?> <!DOCTYPE faces-config PUBLIC "-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.1//EN" "http://java.sun.com/dtd/web-facesconfig_1_1.dtd">
<faces-config > <navigation-rule> <from-view-id>/caterpillar/index.jsp</from-view-id> <navigation-case> <from-outcome>success</from-outcome> <to-view-id>/caterpillar/welcome.jsp</to-view-id> </navigation-case> <navigation-case> <from-outcome>failure</from-outcome> <to-view-id>/caterpillar/index.jsp</to-view-id> </navigation-case> </navigation-rule>
<managed-bean> <managed-bean-name>user</managed-bean-name> <managed-bean-class> com.coolhou.student.jsf.caterpillar.form.UserBean </managed-bean-class> <managed-bean-scope>session</managed-bean-scope> </managed-bean>
</faces-config> |
|
当返回是”success”时,前往welcome.jsp页面,返回是failure时,将送回index.jsp
1.3.3. 修改index.jsp
<%@ page language="java" contentType="text/html;charset=gb2312" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %> <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<!DOCTYPE HTML PUBLIC "-//W 3C //DTD HTML 4.01 Transitional//EN"> <html> <head>
<title>第一个JSF程序</title>
</head>
<body>
<f:view> <h:form> <P><h:outputText value="#{user.errMessage}" /></p> 名称:<h:inputText value="#{user.name}" /><p> 密码:<h:inputSecret value="#{user.password}"></h:inputSecret>
<h:commandButton value="提交" action="#{user.verify}"></h:commandButton> </h:form> </f:view> </body> </html> |
当要根据verify运行结果来决定页面流程时,action属性使用JSF Expression Lanaguage “#{user.verify}”,如此JSF就知道必须根据verify传回的结果来导航页。
<h:outputText>可以取出指定的Bean之属性值,当使用者因验证错误而被送回原页面时,错误信息就可以显示在页面上。