How to get a value from a servlet to jsf-page (xhtml) - java

I have in a servlet a property, I'm setting it's value in the servlet (with getters and setters).
Now, when I want to display the value on the jsf-page (xhtml), it has always the value 0. It's like it looses it'a state.
Servlet:
private int listSize;
private Method SomeMethod(some param){
...some code...
setListSize(int size);
...some code...
}
public int getListSize() {
return listSize;
}
public void setListSize(int size) {
this.listSize = size;
}
xhtml:
<h:outputText value="#{someServlet.listSize}" />

If you use servlet, you can put this value to HttpSession and in xhtml, you call:
<h:outputText value="#{session.getAttribute(yourAttribute)}"/>
Or you use controller, you write:
#ManagedBean
#ViewScoped
public class yourClassName
and in xhtml you call:
<h:outputText value="#{yourClassName.yourVariable}"/>

Related

JSF: invoke method if conversion fails

In JSF, how can I invoke method in case of conversion failing on any of input fields? I guess I can write my own converters and do all the stuff there, but isn't there a more simple way?
You could use a PreRenderViewEvent listener, and in that method check if validation has failed. This listener method will be called every time just before the view is rendered.
E.g.
Consider the following Facelet:
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
>
<h:body>
<h:messages/>
<f:event listener="#{onErrorBean.onPreRenderView}" type="preRenderView" />
<h:form>
<h:inputText value="#{onErrorBean.test}" label="test" required="true" />
<h:commandButton value="Submit" action="#{onErrorBean.onSuccess}" />
</h:form>
</h:body>
</html>
And the following backing bean:
#ViewScoped
#ManagedBean
public class OnErrorBean {
private String test;
public void onPreRenderView() {
if (FacesContext.getCurrentInstance().isValidationFailed()) {
onError();
}
}
public void onSuccess() {
System.out.println("Success!");
}
public void onError() {
System.out.println("Error!");
}
public String getTest() {
return test;
}
public void setTest(String test) {
this.test = test;
}
}
If you press the button without entering a value you'll see "Error!" being printed in your console, enter a value and you'll see "Success!".

Reloading the same page based on a toggle button preserving the paramters

I have a page where I have a static list containing the list of products which are again grouped into product groups.I have a toggle button in the JSP page which shuffles between the enabled and disabled products .Code for my toggle button is as follows
<h:commandButton value="retrieve" image="#{displayProductsBean.productsToggleImage}" actionListener="#{displayProductsBean.fetchProductsBasedOnStatus}">
<c:choose>
<c:when test="${displayProductsBean.productFetchCriteria=='0'}">
<f:attribute name="buttonSelected" value="1" />
</c:when>
<c:otherwise>
<f:attribute name="buttonSelected" value="0" />
</c:otherwise>
</c:choose>
</h:commandButton>
Now in the managed bean I am able to get the value of the button selected and have logic to retrieve either enabled or disabled products
But I don't know how would I get back to the same page and also I don't want the list to be reloaded again from the DB.Code in my bean class is as follows
public void fetchProductsBasedOnStatus(ActionEvent event)
{
System.out.println("The fetchProductsBasedOnStatus in bean is called");
String selected = (String) event.getComponent().getAttributes().get("buttonSelected");
System.out.println("The value of toggle button is"+selected);
setProductFetchCriteria(Integer.parseInt(selected));
System.out.println("The value of toggle button is"+this.toString());
}
Somebody please help me resolve this .....
But I don't know how would I get back to the same page
Just return null or void in action method.
and also I don't want the list to be reloaded again from the DB
Just don't do that? If you keep the bean in the view scope and load the lists in the (post)constructor, then the same lists will be kept as long as the enduser is interacting with the same view. You should only not use JSTL tags as it breaks the view scope.
Your code can be simplified as follows:
<h:commandButton value="retrieve" image="#{bean.showDisabledProducts ? 'enabled' : 'disabled'}.png" action="#{bean.toggle}">
<f:ajax render="#form" />
</h:commandButton>
<h:dataTable value="#{bean.products}" ...>
...
</h:dataTable>
with
#ManagedBean
#ViewScoped
public class Bean {
private boolean showDisabledProducts;
private List<Product> enabledProducts;
private List<Product> disabledProducts;
#EJB
private ProductService service;
#PostConstruct
public void init() {
enabledProducts = service.listEnabledProducts();
disabledProducts = service.listDisabledProducts();
}
public void toggle() {
showDisabledProducts = !showDisabledProducts;
}
public List<Product> getProducts() {
return showDisabledProducts ? disabledProducts : enabledProducts;
}
public boolean isShowDisabledProducts() {
return showDisabledProducts;
}
}

Getting a GET request param into an #ViewScoped bean

I have a (request-scoped) list from which the user may select a "PQ" (list of links). When clicked or otherwise entered into the browser the main page for each PQ shall be displayed. Each PQ's page is of the form
http://localhost:8080/projectname/main.jsf?id=2
Here's the PQ bean first:
#Named
#ViewScoped
public class PqHome implements Serializable
{
#PersistenceContext(unitName="...")
private EntityManager em;
private Integer id;
private PQ instance;
#PostConstruct
public void init()
{
System.out.println("ID is " + id); // ID from URL param
instance = em.find(PQ.class, id);
}
public Integer getId()
{
return id;
}
public void setId(Integer id)
{
this.id = id;
}
public PQ getInstance()
{
return instance;
}
}
Here's the main.xhtml:
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
...>
<ui:define name="metadata">
<f:metadata>
<f:viewParam name="id" value="#{pqHome.id}">
<f:convertNumber integerOnly="#{true}" />
</f:viewParam>
<!--f:event type="preRenderView" listener="#{pqHome.init}" /-->
</f:metadata>
</ui:define>
<ui:define name="title">
<h:outputText value="Main" />
</ui:define>
...
</ui:composition>
Any time I select or otherwise refresh the page/URL I get a NullPointerException from the EntityManager:
org.jboss.weld.exceptions.WeldException: WELD-000049 Unable to invoke [method] #PostConstruct public de.mycomp.myproj.beans.PqHome.init() on de.mycomp.myproj.beans.PqHome#4f0ea68f
at org.jboss.weld.bean.AbstractClassBean.defaultPostConstruct(AbstractClassBean.java:595)
...
Caused by: java.lang.IllegalArgumentException: id to load is required for loading
at org.hibernate.event.spi.LoadEvent.<init>(LoadEvent.java:87)
at org.hibernate.event.spi.LoadEvent.<init>(LoadEvent.java:59)
at org.hibernate.internal.SessionImpl.get(SessionImpl.java:961)
at org.hibernate.internal.SessionImpl.get(SessionImpl.java:957)
at org.hibernate.ejb.AbstractEntityManagerImpl.find(AbstractEntityManagerImpl.java:787)
at org.hibernate.ejb.AbstractEntityManagerImpl.find(AbstractEntityManagerImpl.java:762)
at org.jboss.as.jpa.container.AbstractEntityManager.find(AbstractEntityManager.java:221)
at de.mycomp.myproj.beans.PqHome.init(PqHome.java:47)
... 56 more
[Line 47 is em.find(...)]
The line
<f:event type="preRenderView" listener="#{pqHome.init}" />
doesn't make things any better. I'm pretty desparate now.
How do you get URL GET request params into an #ViewScoped bean?
Note: I bet it's not a trivial thing to do. Chances are I'm doing something wrong here conceptually, so any tips on how to improve are welcome. I felt that I needed to choose #ViewScoped because there will be more complex AJAX-based GUI on that page which I'd really like to keep accessible via URL GET params.
Thanks
There is a better way to get id from url. Just use it in #PostConstruct init() method to get "id" from url:
FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("id");
You can still use ViewScoped and #PostConstruct.
The #PostConstruct is invoked directly after bean's construction and all dependency injection (such as #PersistenceContext, #EJB, #ManagedProperty, #Inject, etc..etc..).
The <f:viewParam> sets its value during the update model values phase, which is far after (post)construction of the bean. So inside the #PostConstruct the <f:viewParam> value is simply not yet been set. It'll be still null at that point.
You're close with <f:event type="preRenderView">, but you have to remove the #PostConstruct annotation.
So:
<f:viewParam name="pq" value="#{pqHome.id}">
<f:convertNumber integerOnly="#{true}" />
</f:viewParam>
<f:event type="preRenderView" listener="#{pqHome.init}" />
with
private Integer id;
public void init() {
instance = em.find(PQ.class, id);
}
Unrelated to the concrete problem, I'd suggest to use a Converter for this instead. See also Communication in JSF 2.0 - Converting and validating GET request parameters.
Also the combination #Named #ViewScoped won't work as intended. The JSF-specific #ViewScoped works in combination with JSF-specific #ManagedBean only. Your CDI-specific #Named will behave like #RequestScoped this way. Either use #ManagedBean instead of #Named or use CDI-specific #ConversationScoped instead of #ViewScoped.

how to move a variable's value from jsf's bean page (i.e, bean.java) to another java class?

how to move a variable's value from jsf's bean page (i.e, bean.java) to another java class? when i tried to do that, the value assinged to the variable in the second java class is NULL.,
I have used primefaces UI framework(something like jsf) and assigned every fields value in to a bean class. the value assigned to every variable in bean class is proper. but when i tried to move those values to another .java file. The scope of the variable dies, and the value is NULL. Check out my codings..
LOGIN.XHTML
<!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"
xmlns:p="http://primefaces.prime.com.tr/ui">
<h:head></h:head>
<h:body>
<p:panel header="Login" style="">
<h:form>
<h:panelGrid columns="2" cellpadding="2">
<h:outputText value="Username"></h:outputText>
<p:inputText id="userName" value="#{loginBean.userName}"></p:inputText>
<h:outputText value="Password"></h:outputText>
<p:password id="password" value="#{loginBean.password}"></p:password>
<p:commandButton value="Sign in" ajax="false" actionListener="#{loginBean.forward}"></p:commandButton>
</h:panelGrid>
</h:form>
</p:panel>
</h:body>
</html>
loginBean.java
package bean;
import receive.*;
public class loginBean {
public String userName;
public String password;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public void forward()
{
System.out.println(getUserName());
receiveclass r=new receiveclass();
r.dbc();
}
}
receiveclass.java
package receive;
import bean.loginBean;
public class receiveclass {
loginBean lb=new loginBean();
public void dbc()
{
String s= lb.getUserName();
String p=lb.getPassword();
System.out.println(s);
System.out.println(p);
//System.out.println("hi");
}
}
output is,
if i give as admin, admin in text fields
i am receiving as
admin
null
null
You're manually creating the beans instead of letting JSF manage the beans. Manually created beans won't be used by JSF at all. You need to let JSF auto-create and manage those beans. You can access other JSF managed beans by injecting it as #ManagedProperty:
In your particular case, the following should work:
#ManagedBean
#RequestScoped
public class LoginBean {
private String userName;
private String password;
#ManagedProperty
private ReceiveClass receiveClass;
public void forward() {
receiveClass.dbc(this);
}
// Add/generate getters and setters.
}
with
#ManagedBean
#SessionScoped
public class ReceiveClass {
public void dbc(LoginBean loginBean) {
System.out.println(loginBean.getUserName());
}
}
(Note that I fixed the code to adhere the Java Naming Conventions properly. Class names ought to start with uppercase)
See also:
Communication in JSF 2.0 - Injecting managed beans in each other
in your receiveclass you create a completely new instance of loginBean. Values can only be null.
I do it this way: I created a Java class in which I have static functions like this one
public class JSFHelper
{
public static Object getMyObject(String objname, Class<?> classname )
{
FacesContext fCtx = FacesContext.getCurrentInstance();
ELContext elCtx = fCtx.getELContext();
ExpressionFactory ef = fCtx.getApplication().getExpressionFactory();
ValueExpression ve =
ef.createValueExpression(elCtx, "#{" + objname+ "}",classname);
return (Object) ve.getValue(elCtx);
}
}
If I need a value from another Bean it would look like this in your receiveclass:
public class receiveclass
{
public void dbc()
{
loginBean lb=(loginBean)JSFHelper.getMyObject("loginBean",loginBean.class);
String s= lb.getUserName();
String p=lb.getPassword();
System.out.println(s);
System.out.println(p);
//System.out.println("hi");
}
}

<h:inputText> howto execute bean method on blur?

I have <h:inputText> on form and what I need is to execute some method from backing bean on BLUR event:
public void test()
{
System.out.print("HELLO!");
}
Can you help me?
You can use <f:ajax>
<h:form>
<h:inputText value="#{managedBean.val}" >
<f:ajax event="blur" render="result" listener="#{managedBean.test}"/>
</h:inputText>
</h:form>
#ManagedBean(name = "managedBean")
public class Bean {
private String val; // getter and setter
...
public void test() {
System.out.print("HELLO!");
}
}
Alternative :
If you are using richfaces then you can use a4j:jsFunction
See Also
JSF2: Ajax in JSF – using f:ajax tag
How-to-update-a-value-displayed-in-the-page-without-refreshing

Categories