我尝试AJAXify一个简单的commandButton以便发送AJAX请求而不刷新整个页面。我的xhtml文件包含以下代码:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Test</title>
</h:head>
<h:body>
<h:form id="form">
<h:inputText id="name" value="#{test.name}"></h:inputText>
<h:commandButton value="Welcome Me">
<f:ajax execute="@form" render="@form" />
</h:commandButton>
<h2>
<h:outputText id="output" value="#{test.sayWelcome}" />
</h2>
</h:form>
</h:body>
</html>
我的后备豆如下:
import java.io.Serializable;
import javax.faces.bean.ViewScoped;
import javax.inject.Named;
@ViewScoped
@Named("test")
public class TestBackingBean implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSayWelcome() {
// check if null?
if ("".equals(name) || name == null) {
return "";
} else {
return "Ajax message : Welcome " + name;
}
}
}
但是,当我单击commandButton时,将提交表单并刷新整个页面。
我想避免使用其他JSF框架。
谢谢。
答案 0 :(得分:0)
您可以尝试执行和渲染属性吗?
<h:form id="form">
<h:inputText id="name" value="#{test.name}"></h:inputText>
<h:commandButton value="Welcome Me" action=#{test.sayWelcome()}>
<f:ajax execute="name" render="output" />
</h:commandButton>
</h:form>
<h2> <!-- Outside the Form! -->
<h:outputText id="output" value="#{test.message}" />
</h2>
Bean:
public class TestBackingBean implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private String message;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMessage() {
return message;
}
public void setMessage(String value) {
this.message = value;
}
public void sayWelcome() {
// check if null?
if ("".equals(name) || name == null) {
message = "";
} else {
message = "Ajax message : Welcome " + name;
}
}
}
答案 1 :(得分:0)
这里的问题是您使用了错误的@ViewScoped
。是a mess that's a long time in the making,我想表示哀悼。
您拥有的@ViewScoped
版本并不意味着可以与CDI的@Named
一起使用。结果,您实际上在那里没有一个可查看范围的bean-该bean在隐式CDI @Dependent
范围内,其行为有点像@RequestScoped
范围。
简而言之:改用javax.faces.view.ViewScoped
批注,您的bean将正常运行。