mar*_*zzz 4 ajax jsf facelets jsf-2
我认为这个主题解释了我在寻找什么:
template.xhtml
<div class="content">
<ui:insert name="content_homepage">Box Content Here</ui:insert>
</div>
Run Code Online (Sandbox Code Playgroud)
index.xhtml
<ui:composition template="./template.xhtml">
<ui:define name="title">
JSF - The Sinfonet Portal
</ui:define>
<ui:define name="login">
<h:form id="form1" prependId="false">
<h:outputScript name="jsf.js" library="javax.faces" target="head" />
<span class="menu_span">Username</span>
<h:inputText value="#{login.name}" id="name" />
<span class="menu_span">
<h:commandButton value="Login" action="#{login.checkLogin}">
<f:ajax event="action" execute="name" render="??????"/>
</h:commandButton>
</span>
</h:form>
</ui:define>
<ui:define name="content_homepage">
<span class="content_title">Homepage</span>
</ui:define>
<ui:define name="content_logged">
<span class="content_title">OK. You are logged</span>
</ui:define>
</ui:composition>
Run Code Online (Sandbox Code Playgroud)
管理豆
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
@ManagedBean(name="login")
@RequestScoped
public class Login {
private String name = "";
public String getName() { return name; }
public void setName(String newValue) { name = newValue; }
public boolean checkLogin() {
if(name.length()==0) {
return true;
} else {
return false;
}
}
}
Run Code Online (Sandbox Code Playgroud)
通过使用模板定义,我插入第content_homepage一个内容.之后,当我进行ajax调用时,如果名称不为空,我将加载content_login.是否可以在JSF上执行此操作?
干杯
您需要将Facelets(视图/模板技术)和JSF(基于组件的MVC框架)的概念分开.由于Facelets ui标签仅是服务器端并且不向客户端发出任何内容,因此单独的Facelets无法实现您想要的功能.您需要引入一个JSF组件(在HTML结束时生成),它可以由客户端的JS/Ajax定位.
template.xhtml
<h:panelGroup layout="block" id="content">
<ui:insert name="content_homepage">Box Content Here</ui:insert>
</h:panelGroup>
Run Code Online (Sandbox Code Playgroud)
(在layout="block"使它成为<div>代替的<span>)
按钮index.html:
<h:commandButton value="Login" action="#{login.checkLogin}">
<f:ajax execute="@form" render=":content" />
</h:commandButton>
Run Code Online (Sandbox Code Playgroud)
(:content指的<h:panelGroup id="content">是位于上层:)
内容模板定义index.html:
<ui:define name="content_homepage">
<h:panelGroup rendered="#{!login.loggedIn}">
User is not logged in.
</h:panelGroup>
<h:panelGroup rendered="#{login.loggedIn}">
User is logged in.
</h:panelGroup>
</ui:define>
Run Code Online (Sandbox Code Playgroud)
管理豆:
private String name; // Do NOT initialize with empty string! Poor practice.
// ...
public boolean isLoggedIn() { // Boolean getter methods should be prefixed with `is`.
return name != null; // Do NOT add if/else verbosity for something which already returns boolean! Poor practice.
}
Run Code Online (Sandbox Code Playgroud)
此外,不要使用跨度作为标签.这是糟糕的HTML语义.使用<h:outputLabel>(或纯HTML <label>).