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...
}
Test.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>