现在的位置: 首页 > 综合 > 正文

JSF 2.0简单示例

2012年10月05日 ⁄ 综合 ⁄ 共 1813字 ⁄ 字号 评论关闭

和Java EE 6一起来的JSF 2.0虽然动静不是很大,但SUN在Java EE 6 Tutorial中的一些表态比较明显。

 

JSP is considered as a deprecated presentation technology for JavaServer Faces 2.0.

存档个小例子:前端是两个xhtml, request/response, 他们调用后台的managed bean完成逻辑。

其中有些说明:

1、@ManagedBean 表示用于JSF的托管Bean

2、@SessionScoped表示生命周期

3、类名和属性名称在这里首字母小写了

 

Request.xhtml

代码
<?xml version="1.0" encoding="UTF-8"?>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h
="http://java.sun.com/jsf/html"
      xmlns:f
="http://java.sun.com/jsf/core">
    
<h:body>
        
<h:form>
            
<h:inputText id="x" value="#{calcBean.x}">
                
<f:validateLongRange minimum="#{calcBean.min}" maximum="#{calcBean.max}"/>
            
</h:inputText>
            
<h:inputText id="y" value="#{calcBean.y}">
                
<f:validateLongRange minimum="#{calcBean.min}" maximum="#{calcBean.max}"/>
            
</h:inputText>

            <h:commandButton id="submit" value="calc" action="response.xhtml"/>
        
</h:form>
    
</h:body>
</html>

Response.xhtml

代码
<?xml version="1.0" encoding="UTF-8"?>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h
="http://java.sun.com/jsf/html">
    
<h:body>
        
<h:outputLabel value="#{calcBean.response}"/>
    
</h:body>
</html>

Bean Code

代码
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

@ManagedBean
@SessionScoped
public class CalcBean {
    
int x;
    
int y;

    static final int MAX = 20;
    
static final int MIN = 10;

    public String note(){
        
return "Calculator";
    }

    public int getX(){
        
return x;
    }

    public int getY(){
        
return y;
    }

    public void setX(int newVal){
        x 
= newVal;
    }

    public void setY(int newVal){
        y 
= newVal;
    }
    
    
public int getResponse(){
        
return x + y;
    }

    public int getMax(){
        
return MAX;
    }

    public int getMin(){
        
return MIN;
    }

}

 效果:

1、输入不合规范数据:

 

2、输入合规数据

 

抱歉!评论已关闭.