您可以在 bean 构造函数中初始化页面的值:
TestBean 类
@ManagedBean
@ViewScope
public class TestBean {
private String name;
public TestBean() {
//initialize the name attribute
//recover the value from session
HttpSession session = (HttpSession)FacesContext.getCurrentInstance()
.getExternalContext().getSession(false);
name = session.getAttribute("name");
if (name == null) {
name = "Luiggi";
}
}
public String someAction() {
//save the value in session
HttpSession session = (HttpSession)FacesContext.getCurrentInstance()
.getExternalContext().getSession(false);
session.setAttribute("name", name);
return "Test";
}
//getters and setters...
}
测试.xhtml
<ui:composition
xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html">
<h:body>
<h:outputText value="Hello " />
<h:outputText value="#{testBean.name}" />
<h:form>
<h:outputText value="Write your name: " />
<h:inputText value="#{testBean.name}" />
<br />
<h:commandButton value="Change name" action="#{testBean.someAction}" />
</h:form>
</h:body>
</ui:composition>
添加示例以在导航到 Text.xhtml 之前删除会话属性
SomeBean 类
@ManagedBean
@RequestScope
public class SomeBean {
public SomeBean() {
}
public String gotoTest() {
//removes an item from session
HttpSession session = (HttpSession)FacesContext.getCurrentInstance()
.getExternalContext().getSession(false);
session.removeAttribute("name");
return "Test";
}
}
SomeBean.xhtml
<ui:composition
xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html">
<h:body>
<h:form>
<!-- Every time you navigate through here, your "name"
session attribute will be removed. When you hit the back
button to get Test.xhtml you will see the "name"
session attribute that is actually stored. -->
<h:commandButton value="Go to Test" action="#{someBean.gotoTest}" />
</h:form>
</h:body>
</ui:composition>