This question already has answers here:
How to dynamically add JSF components
(3 answers)
Closed 7 years ago.
I'm writing an application that serves as an admin panel using JSF 2.0 and Hibernate. I have a JSP page with a JSF form which elements are added dynamically using javascript (jQuery to be specific). So I cannot make any assumption on how much data do I have to process. I have a managed bean but I don't know how to put the getters and setters for the dynamic fields that I want to save in a database. The solution seems to use a list rather than a single element but how do I use the value tag of the JSF element? Could it be something like this:
<h:form>
<h:inputText id="i1" value="#{UserBean.list}" />
<h:inputText id="i2" value="#{UserBean.list}" />
<h:commandbutton id="submit" value="Submit" action="#{UserBean.submit}"/>
</h:form>
And the managed bean:
#ManagedBean(name="UserBean")
#RequestScoped
public class UserBean {
public UserBean() {
List<String> list = null;
}
public List getList() {
return list;
}
public List setList(List<String> newlist) {
list = newList;
}
}
However, the above code does not seem correct and certainly does not work. I need to bind two or more values of the inputtext to the same list. Does anyone have any suggestions how to solve it? Thanks in advance.
Regards,
sass.
You can't directly add JSF components dynamically using jQuery. All jQuery can is traversing and manipulating "plain vanilla" HTML DOM tree at the client side. It has totally no notion of the JSF component tree as it is generated and maintained in the server side. JSF in turn knows nothing about the state changes in the HTML DOM tree done by "plain vanilla" jQuery/JavaScript since it doesn't notify JSF on the server side about the changes. JSF relies on the JSF component tree to process form submits, not the HTML DOM tree.
You want to change the JSF component tree dynamically using JSF. Since this is going to be a long story to explain in detail, here are some links to similar questions I answered before to get you started:
How to add JSF components dynamically - This should be exactly what you need.
How to create dynamic JSF form - This does it the "other way round", just in case you're interested.
You can use primefaces extension dynaform. where you can create form dynamic.
See this link
http://fractalsoft.net/primeext-showcase-mojarra/views/dynaForm.jsf
Related
I'm new to JSF and developing web applications with Java.
I'm basically developing a pretty complex interface, with lots of AJAX content loaded (Pagination, posts, comments, ...).
I'll start with a basic example, a user writes a comment. The form is sent through JSF f:ajax to the server and then I can do a render="sectionId", but the problem is, that I want to make the post not just appear, but slide down and even toggle background color.
How can I obtain this sort of effect using JSF and Javascript?
The designer (who knows only HTML/CSS/Javscript/Jquery) says that usually, he just does a Jquery AJAX call to a page with a string of data and then the page generates a JSON encode that he can then use to do all the magic.
I'm not asking how you do the toggle/color in jquery, it's the communication between the JSF and Javascript. So how can I send to his javascript the newly generated HTML code, so that he can what he wants with it.
Thanks for any help.
JSF is a server-side technology and you'd typically conditionally display content within
a construct such as a panelGroup, so why not include your jquery magic inside a ready
handler inside the conditionally rendered panelGroup like this:
<h:panelGroup id="ajaxRenderTarget">
<ui:repeat value="#{bean.listOfComments}" var="var">
... display required information ...
</ui:repeat>
<h:panelGroup rendered="#{bean.showJqueryEffects}">
<script type="text/javascript">
jQuery(function($) {
... funky effects here ...
});
</script>
</h:panelGroup>
</h:panelGroup>
Where I've used ui:repeat in the above example you could be and probably would be using any data iteration component from jsf or a component library such as a datatable.
Another thing to consider is OmniFaces which has <o:onloadScript> and a host of other tags which are worth knowing about.
One mistake to avoid is trying to load JSF pages using jQuery ajax functions, the server will have no state of the component tree and it won't work.
Is there a way to have a JSF Backing bean cause an update of a component on the page? I am not looking to use an ajax component with update attribute to update a component on the page. I need to trigger an update from within a JSF backing bean method. Note the update on the page can happen after this method completes or prior to its completion. I am using PrimeFaces, if there is a solution that can be had from using PrimeFaces.
Using standard JSF API, add the client ID to PartialViewContext#getRenderIds().
FacesContext.getCurrentInstance().getPartialViewContext().getRenderIds().add("foo:bar");
Using PrimeFaces specific API, use PrimeFaces.Ajax#update().
PrimeFaces.current().ajax().update("foo:bar");
Or if you're not on PrimeFaces 6.2+ yet, use RequestContext#update().
RequestContext.getCurrentInstance().update("foo:bar");
If you happen to use JSF utility library OmniFaces, use Ajax#update().
Ajax.update("foo:bar");
Regardless of the way, note that those client IDs should represent absolute client IDs which are not prefixed with the NamingContainer separator character like as you would do from the view side on.
I also tried to update a component from a jsf backing bean/class
You need to do the following after manipulating the UI component:
FacesContext.getCurrentInstance().getPartialViewContext().getRenderIds().add(componentToBeRerendered.getClientId())
It is important to use the clientId instead of the (server-side) componentId!!
The RequestContext is deprecated from Primefaces 6.2. From this version use the following:
if (componentID != null && PrimeFaces.current().isAjaxRequest()) {
PrimeFaces.current().ajax().update(componentID);
}
And to execute javascript from the backbean use this way:
PrimeFaces.current().executeScript(jsCommand);
Reference:
https://github.com/primefaces/primefaces/wiki/Migration-Guide
https://forum.primefaces.org/viewtopic.php?t=53129
Everything is possible only if there is enough time to research :)
What I got to do is like having people that I iterate into a ui:repeat and display names and other fields in inputs. But one of fields was singleSelect - A and depending on it value update another input - B.
even ui:repeat do not have id I put and it appeared in the DOM tree
<ui:repeat id="peopleRepeat"
value="#{myBean.people}"
var="person" varStatus="status">
Than the ids in the html were something like:
myForm:peopleRepeat:0:personType
myForm:peopleRepeat:1:personType
Than in the view I got one method like:
<p:ajax event="change"
listener="#{myBean.onPersonTypeChange(person, status.index)}"/>
And its implementation was in the bean like:
String componentId = "myForm:peopleRepeat" + idx + "personType";
PrimeFaces.current().ajax().update(componentId);
So this way I updated the element from the bean with no issues. PF version 6.2
Good luck and happy coding :)
In order to updte the component from backing bean, we can achieve as below
RequestContext.getCurrentInstance().update('updatePanelGroup');
<h:panelGroup id="updatePanelGroup">
.....
....
</h:panelGroup>
Updating the component differs with respect to prima face version.
i have done some learning on struts based on one project that i got.Now i have to build 2 to 3 struts jsp pages.
I have following scenario..
<action name="BackAction" class="ClassnamePath">
<result name="user_validated" type="redirectAction">
<param name="actionName">welcome</param>
</result>
<result name="user_profile_found_in_database">/resources/userprofile.jsp</result>
what does param will tell..what is the significance of param(i do not know about this)
my scenario is like this In the class(ClassnamePath) i have done one java program which bring the data from the database and put the values in the userprofile.java(for example the userprofile has variable members like name,email,phone,pin)
that values are come from database and stored in the object of the class userprofile.
i have a task that whenever the result "user_profile_found_in_database" has been done those values should be presented in the jsp as result of the "user_profile_found_in_database"
Is the result "user_profile_found_in_database" that i mentioned in the action tag correct?
the jsp page should be having userprofile with labels as the fields of the userprofile and values should be in the text boxes.
i do not know anything about jsp pages...even web programming..but i am learning on my own..(i am having one doubt how jsp pages are different from struts jsp pages)
with the above tasks i can learn lot in struts and jsp..
Please give some knowledge on this to build further.
JSP pages are not way different than simple JSP pages and in short Struts2 will provides a set of tags which will help we as an end developer to build application fast as these tags provides a easy to access functionality about various features S2 providing, few of them are
Accessing Value Stack using OGNL
Data conversion from server to client and other way around
Features to access other things like request/response/session in most easy and flexible way.
In end when you browser will render the jsp page it will be simple HTML and S2 tags one using in there application will be converted to the HTML as browser will understand HTML.
regarding second part accessing user profile in your jsp do the following gin your Action class
Create an instance of UserProfile in you action class
Create getter and setter for the UserProfile instance
Fill the value in the user-profile (you will fetch that from your DB call)
when your action will send back the response, S2 will place the user-profile instance on top of Value stack and we can access its properties using S2 tags like
<s:textfield name="user_name" value="%{name}"/>
<s:textfield name="user_age" value="%{age}"/>
here name and age are the properties of your user-profile.param in your redirectAction configuration is being used to provide parameters to the result, for more information about what parameters do please read official document.
redirect-action-result
.
Ya i got your question like this,
what is the exact meaning of param tag?
param tag means:
Struts 2 “param” tag is used to parametrize other tags. However, when you declared the “param” tag, the “parameter value” can be define in two ways :
“value” attribute
Text between the start and end of “param” tag.
For Example:
<param name="fruit">Banana</param>
<param name="fruit" value="Banana"/>
In Your example the 1st case i think
Here see this web site it is present complete structure...
http://www.mkyong.com/struts2/struts-2-param-tag-example/
This question already has answers here:
How to populate options of h:selectOneMenu from database?
(5 answers)
Closed 6 years ago.
Up until now, I have always been using JSP to display pages. When a user request for a page such as "Add Item", I will load all Item Category in an Array List and display them as options in select box like this:
<select name="category>
<%
ArrayList<Category> categories = (ArrayList<Category>) request.getAttribute("categories");
for (Category c : data) {
%>
<option value="<%= c.getId() %>"><%= c.getName() %></option>
<%
}
%>
</select>
From the book "JavaServer Faces 2.0, The Complete Reference", I learnt that: "JSF enforces clean Model-View-Controller separation by disallowing the inclusion of Java code in markup pages". Hence, I'd be very grateful if someone could show me how I can handle the above task using JSF since I cannot use Java code as I have always done anymore.
Best regards,
James Tran
JSF 2.0 uses Facelets as the templating method, which in a nutshell is XHTML with some additional elements.
While technically you can perform method calls from Facelets, in general the idea is to access a JavaBean with proper geter/setter methods to perform your data moving. You can accomplish this as the below segment of code shows:
<h:selectOneMenu value="#{backingBean.selectedCategory}">
<f:selectItems value="#{backingBean.categoryList}"/>
</h:selectOneMenu>
On the bean side of things, you want to expose a bean to JSF using either faces-config (which is largely discouraged) or a mechanism such as CDI or the Managed Bean infrastructure. I highly recommend you look into using SEAM if you go the CDI route, as it will unify the (currently really strangely disparate) Managed Bean and CDI frameworks, so you can use JSF scopes in CDI, and have CDI beans available in JSF scopes.
#ManagedBean(name="backingBean")
#ViewScoped
public class MyJavaBackingBean {
#ManagedProperty("#{param.categories}")
protected List<String> categoryList
public void setSelectedCategory(String value) {
this.selectedCategory = value;
}
public String getSelectedCategory() {
return this.property;
}
...
}
You can also make the getters do lazy initialization of your values (for pulling categoryList from a database for example), and use some other JSF annotations to do various initialization tasks.
You can also code action methods which return a String representing the JSF action (this gets coded into your faces-context.xml file) to take after returning. Phase listeners on the backing bean can also be called at various stages of page rendering, validation and submission, getting you very fine grained control.
categoryList in the above example is not limited to basic types of course, and <f:selectItems> also has some syntax for writing out the textual version of your select items, so you can make some quite complex expressions to display each item in a friendly way.
Create a bean and make it known with e.g. #Named so you can refer to it from your JSF script. Then give that bean a method returning the data you want to show, and invoke that method from your JSF script in a location where that data is expected e.g. a loop construct.
Store the data you want to display in a Java list, and expose that list as a property of a backing bean. The use the appropriate JSF tag to display that property.
In JSF 2.0 you can include the tag h:selectOneMenu in which you get the value where you store the item value selected. The value in f:selectItems could be a collection of any object the most of times SelectItem in this object your declare value object and the label to display.
<h:selectOneMenu value="#{backingBean.selectedvalue}">
<f:selectItems value="#{backingBean.List}"/> </h:selectOneMenu>
if you required values and labels of another object in you must declare
<h:selectOneMenu value="#{backingBean.selectedvalue}">
<f:selectItems value="#{backingBean.ListCar}" var="car" itemLabel="#{car.model}" itemValue="#{car.modelId}"/>
</h:selectOneMenu>
I would like to basically do what Jason asked for here
In one sentence, I would like the url bar to represent the state of the AJAX application so that I can allow to bookmark it as well as allow the user to return to the previous state by using the back/forward buttons in the browser.
The difference for me (From what Jason asked) is that I am using JSF 2.0.
I've read that JSF 2.0 added the ability to use get, but I am not sure what the correct way to use this.
Thanks for the help.
Further Clarification
If I understand correctly, to be able to bookmark specific states in the AJAX webapp I will have to use the location.hash. Am I correct? I'm trying to achieve a gmail-like behaviour in the sense that, while the app is complete AJAXified and no redirects occur, I can still use Back/Forward and bookmark (And that's why I would like the URL bar to be updated from the AJAX app itself and not through redirection)
Update
Just found this similar question
The difference for me (From what Jason asked) is that I am using JSF 2.0. I've read that JSF 2.0 added the ability to use get, but I am not sure what the correct way to use this.
Please note that this is not the same as maintaining the Ajax state. It usually happens by fragment identifiers (the part starting with # in URL, also known as hashbang). JSF doesn't offer builtin components/functionality for this. As far I have also not seen a component library which does that. You may however find this answer useful to get started with a homegrown hash fragment processor in JSF.
As to using GET requests, just use <h:link>, <h:outputLink> or even <a> to create GET links. You can supply request parameters in the h: components by <f:param>. E.g.
<h:link value="Edit product" outcome="product/edit">
<f:param name="id" value="#{product.id}" />
</h:link>
In the product/edit.xhtml page you can define parameters to set and actions to execute upon a GET request
<f:metadata>
<f:viewParam name="id" value="#{productEditor.id}" />
<f:event type="preRenderView" listener="#{productEditor.init}" />
</f:metadata>
In the request or view scoped bean associated with product/edit.xhtml page -in this example #{productEditor}-, you just define the properties and the listener method. The listener method will be executed after all properties are been gathered, converted, validated and updated in the model.
private Long id;
private Product product;
public void init() {
product = productService.find(id);
}
Normally you'd use AJAX to prevent complete page refreshes. AFAIK all current browsers would issue a page refresh if you change the base uri. Thus you would have to use the hash part as suggested in the question you provided.
We had a similar problem and did something like this:
We settled for the fact that users cannot bookmark the url.
For URLs that should be unique/bookmarkable we used different links that issue a redirect. Those URLs are provided in a sitemap.
For browser back, we added an intermediate page after login. This page does navigation and a redirect to the application. The navigation is stored in the session and when the server gets a navigation request (which can be a history back) the corresponding state is restored. A browser back opens that intermediate page which issues a redirect along with a navigation request on the server side.