Making view transient does not seem to work in JSF 2 - java

I have a home page that is written in JSF 2.2. It uses a public template that is shared by many other pages. I don't want to include <f:view transient="true"> in the public template because I want to make only this particular home page as transient.
Now I have this code in my home page
<f:view transient="true">
<ui:define name="content">
.....
<h:commandLink value="#{msg['homepage.createaccount']}"
action="#{homepageController.createNewAccount()}" />
</ui:define>
</f:view>
now HomepageController is a named session bean.
#Named
#Session
public class HomepageController {
//code here
}
The <f:view = "transient"> does not seem to work. Is it because the controller is Session scoped ?
The controller is session scoped because while loading the first page, we fetch several important lists that are used later by many parts of application.

Related

How to make a form tag comunicate to another form tag?

I am using JSF 2.2, PrimeFaces and Glassfish and I have this:
<h:form id="formularioAltas">
//more code
<p:commandButton value="Guardar" action="#{altasBean.agregarRefaccion()}" />
</h:form>
<h:form id="myForm" enctype="multipart/form-data" prependId="false" rendered="#{altasBean.estado}">
// more code here
</h:form>
And I need formularioAltas to tell myForm that the value of the boolean property estado has changed. I uderstand it like doing a simple update to myForm when the commandButton is executed but that cant be cause they are in diferent forms. I needed this way cause I have problems uploading files to the server so I decided to use two different forms. I have working this forms but I want to show only myForm when the commandButton is executed.
Any ideas?
<p:commandButton value="Guardar" action="#{altasBean.agregarRefaccion()}" update=":myForm" />
: because you climb the container hierarchy one step up to the container which contains both forms and myForm because that's her name.

Templates in JavaServer Faces 2.0

I'm trying for the first time to use templates with JSF 2.0 with Eclipse, but I'm having problems.
The original index.xhtml page works correctly, and when I click on a button, everything works fine. However, if I change the index page so that it uses a template file it no longer works properly. The modified index.xhtml page is here:
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
template="/templates/main-template.xhtml">
<ui:define name="title">
Simulator using JSF 2.0 - Test Version 2
</ui:define>
<ui:define name="header">
Home Page of the Simulator using JSF 2.0 - Test Version 2
</ui:define>
<ui:define name="body">
Click on the button to select the required option
<h:outputText value="and login" rendered="#{!login.loggedIn}"/>
<h:form prependId="false">
<h:commandButton value="Option 1" action="#{login.option1}"/>
<h:commandButton value="Option 2" action="#{login.option2}"/>
<h:commandButton value="Option 3" action="#{login.option3}"/>
<h:commandButton value="Logout" disabled="#{!login.loggedIn}" action="#{login.logout}"/>
</h:form>
</ui:define>
</ui:composition>
and the template file, main.template.xhtml, is in the sub-folder templates, is here:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html">
<h:head>
<title>
<ui:insert name="title">Title</ui:insert>
</title>
</h:head>
<h:body>
<ui:insert name="header">Header</ui:insert>
<br/>
We are in template.xhtml
<br/>
<ui:insert name="body">Body</ui:insert>
</h:body>
</html>
If I remove all code with the "h" tags in index.xhtml, the file picks up correctly the code in templates/main-template.xhtml, so the path is correct. However, if I include code with the "h" tags, as is here, Eclipse complains that the tags are not recognized and the page fails.
If I include the line xmlns:h="http://java.sun.com/jsf/html" at the top, then Eclipse recognized the "h" tags and the page is correctly rendered, but the application fails when I click a button, and returns the error:
javax.servlet.ServletException: javax.el.PropertyNotFoundException:
/index.xhtml #15,68 action="#{login.option1}": Target Unreachable,
identifier 'login' resolved to null
Perhaps somehow the line xmlns:h="http://java.sun.com/jsf/html" in the template file is messing things up, but the whole idea of templates is to include as much common code in a template file.
Does anybody have any idea what is going on, and what the solution to this is?
The web.xml and faces-config.xml are standard, and don't think anything has to be done with them.
Your idea of how templates should work seems correct, but there are some points that we should clarify. Maybe this would help you:
Namespaces
About namespaces, whenever you use a tag library in a page, you should declare it's namespace. Even if you're using templates and you've declared them in your template. You could think that namespace declarations are not inherited, if it helps.
In this case I see that you index.xhtml page is using h:commandButton but hasn't declared its namespace.
Beans
For a bean to be found by EL you should have the following:
A class annotated with #ManagedBean importing from javax.faces.bean.ManagedBean package, like this:
import javax.faces.bean.ManagedBean;
#ManagedBean
#ViewScoped
public class Login
{
// ...
}
In this case your bean should be found by EL by the name login, by convention. (Decapitalize the first letter of your class name)
Or you could give it a name:
import javax.faces.bean.ManagedBean;
#ManagedBean(name="login")
#ViewScoped
public class MyLoginBean
{
// ...
}
In this case, by convention it would be called myLoginBean but we gave it a name, in this case login, so EL should find it by the name login.
If you want to use CDI instead of plain JSF, you could use #Named annotation to define how your bean should be found by EL, following the same naming convention.
import javax.inject.Named;
import javax.enterprise.context.RequestScoped;
#Named(value="login")
#RequestScoped
public class MyLoginBean
{
// ...
}
Remember that data that you want EL to find and change must have the proper getters and setters.
Hint
I would kindly suggest that you create simpler code in order to test funcionality. In this case you could test templating first and then bean, actions, etc...
I hope it helps.

JSF 2 - construct a page from two files - main and current content

I'm quite new to using JSF and I'm not sure if that's the right way to go, but in Rails you usually have a main application file into which the current page is loaded. That way I don't have to worry about copy-pasting the menu, etc. every time.
How can I achieve that with JSF 2? Can I navigate to the same main page every time and tell it to load a current content? Or do I tell the current page that I navigate to to load the "main frame around the content"?
Thanks!
Yes of course, JSF 2.0 has page-templating feature. You define a template that defines a generic layout to all the view pages.
Facelets tags to create basic page:
ui:insert – defines content that is going to replace by the file that load the template;
ui:define – defines content that is inserted into tag ui:insert;
ui:include – includes content from another page;
ui:composition – the specified template is loaded, if used with template attribute, and the children of this tag defines the template layout. In other case, it’s a group of elements, that can be inserted somewhere.
For example:
<ui:composition
xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
template="/templates/myLayout.xhtml">
<ui:define name="menu">
<ui:include src="/mypath/menu.xhtml"/>
</ui:define>
<ui:define name="content">
<ui:include src="/mypath/content.xhtml"/>
</ui:define>
</ui:composition>
or
<ui:insert name="content">
<ui:include src="/mypath/mycontent.xhtml"/>
</ui:insert>
JSF doesn't support what you want to archive. Instead, it support the views and basic layout(template). What you need it this:
<?xml version="1.0" encoding="UTF-8"?>
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
template="path/to/template.xhtml>
<your custom content here/>
<ui:composition/>

Conversation not propagated automatically on form submission?

I have the following conversation scoped backing bean:
#Named
#ConversationScoped
public class TestConversation implements Serializable {
private Logger logger = LoggerFactory.getLogger(TestConversation.class);
private List<Integer> numbers;
#Inject
private Conversation conversation;
#PostConstruct
public void init() {
logger.info("Creating TestConversation bean!!!");
numbers = new ArrayList<Integer>();
numbers.add(3);
numbers.add(4);
numbers.add(5);
numbers.add(6);
conversation.begin();
}
public void commandLinkAction() {
logger.info("Invoking commandLinkAction");
}
public List<Integer> getNumbers() {
return numbers;
}
}
And the following facelets view:
<!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:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<title>Testing Conversation</title>
</h:head>
<h:body>
<h:form>
<h:dataTable value="#{testConversation.numbers}" var="num">
<h:column>
<h:outputText value="#{num}"/>
</h:column>
<h:column>
<h:commandLink action="#{testConversation.commandLinkAction}">Trigger form submission</h:commandLink>
</h:column>
</h:dataTable>
</h:form>
</h:body>
</html>
When I enter the page I see INFO: Creating TestConversation bean!!! which is correct.
But then I click on the h:commandLink and I see:
INFO: Creating TestConversation bean!!!
INFO: Invoking commandLinkAction
The bean was created again, which means that the conversation was not propagated. I think this contradicts with the following:
Quote from docs:
The long-running conversation context associated with a request that renders a JSF view is automatically propagated to any faces request (JSF form submission) that originates from that rendered page.
If I add this <f:param name="cid" value="#{javax.enterprise.context.conversation.id}"/> then everything works fine. Do I have a misunderstanding?
P.S Without the f:param it works fine when I click on the commandLink for the second time, but not on the first time:(.
I guess, the problem seems like conversation was not started when the <h:form> component was processed so the form's action did not had cid in it for the first time..
For the second time, when you click on a link, testConversation.commandLinkAction, access to testConversation made the conversation to start before processing the <h:form>
try the below change
If you place #{testConversation} before <h:form>
example works fine as converation is started before processing the <h:form>
Hope this helps..
Building on the previous answer, it's definitely because the TestConversation bean is not being constructed until it's already too late for the form to include the cid automatically.
In this case, you're initializing data for the view, so it's probably better to put it in a preRenderView event listener instead.
<f:event type="preRenderView" listener="#{testConversation.init}"/>
Put this early in your facelet template, such as in the f:metadata (as it's often used in conjunction with f:viewParam), and remove the #PostConstruct annotation. That makes the invocation of init explicit rather than relying on it being run as a side effect of the bean being constructed because it was referenced in an EL expression.

Partial rendering JSF components

dwelling over how to partial render (divs), by including different source files (with panels and components). Depending on menu actions. If understood the JSF phases correctly, the View is rebuilt during the Render Response, the last phase. And if I have events and actions, they will be invoked during the Invoke Application phase, the phase before.
All I want to do is to set the including xhtml page for a specific menu command via ajax, before the View is re-rendered. But the ui:include always get invoked before the menu action. I've tried with richfaces 4 (a4j:param, rich:panel, etc) and standard JSF 2.0 (f:param, h:panelGroup) components, but the the ui:include always get invoked before the action.
What should I do to process the menu action (to set the including page), before the ui:include gets invoked?
PS. This must be the standard patter, instead of including static content. But I find very few examples on this on the net ?!
Menu.xhtml
<rich:toolbar itemSeparator="line">
...
<rich:dropDownMenu mode="ajax">
<f:facet name="label">
<h:panelGroup>
<h:outputText value="Menu 1" />
</h:panelGroup>
</f:facet>
<rich:menuItem id="newActivityMenu" action="#{navigationBean.menuAction}" render="content" label="New">
<a4j:param id="newActivityParam" name="includeContentPage" value="/user/Create.xhtml" />
</rich:menuItem>
...
NavigationBean.Java
#ManagedBean
#RequestScoped
public class NavigationBean {
public String menuAction() {
String param = JsfUtil.getRequestParameter("includeContentPage");
this.includedContentPage = param;
JsfUtil.log(this, "Including Content Page : " +param);
FacesContext.getCurrentInstance().renderResponse();
return "";
}
public String getIncludedContentPage() {
if(includedContentPage == null)
return "";
else if(!includedContentPage.endsWith(".xhtml"))
includedContentPage += ".xhtml";
JsfUtil.log(this, "Get Content Page : " +includedContentPage);
return includedContentPage;
}
layoutClient.xhtml
...
<ui:define name="top">
<ui:include src="/resources/viewComponents/menuTop.xhtml"/>
</ui:define>
<ui:define name="content">
<ui:include src="#{navigationBean.includedContentPage}"/>
</ui:define>
...
masterLayout.xhtml (added)
...
<h:body>
<div id="top" >
<ui:insert name="top">Top Default</ui:insert>
</div>
<div id="left">
<ui:insert name="left">Left Default</ui:insert>
</div>
<ui:insert name="content">Content Default</ui:insert>
</h:body>
..
You must have a template page as well since you are defining top and content in layoutClient.xhtml so I think you are trying to be too general with the layoutClient.xhtml page as it appears to be functioning as a template as well. Lets assume your template page is called template.xhtml. The standard pattern you eluded to is to make your template page something like this:
template.xhtml
...
<ui:insert name="top">
<ui:include src="/resources/viewComponents/menuTop.xhtml"/>
</ui:insert>
...
<ui:insert name="content" />
...
This means that all your pages contain the menu at the 'top' (by default, they can override this) and that they must specify their own content, which makes sense.
Now, instead of trying to make a page like layoutClient.xhtml that does tricky stuff to determine which content is inserted, create each page seperately like this:
page1.xhtml
<ui:composition template="template.xhtml">
...
<ui:define name="content">
<p>This is a page that defines some content and also includes my menu that it inherits from template.xhtml</p>
</ui:define>
...
</ui:composition>
page2.xhtml
<ui:composition template="template.xhtml">
...
<ui:define name="content">
<p>This is another page that defines some content and also includes my menu that it inherits from template.xhtml</p>
</ui:define>
...
</ui:composition>
Both of these pages inherit your menu and put the content in the appropriate place.
With that kind of configuration, all your menuAction() method needs to do is return a link to page1.xhtml or page2.xhtml. Also, you don't need any complex use of parameters or manual calls to renderResponse() or a4j:param tags!

Categories