hello world facelets 2.0 navigation - java

So, I have a backing bean, Foo, and a template with a client, request and response. the clients are redundant, I want just one client.
Clients:
thufir#dur:~$
thufir#dur:~$ cat NetBeansProjects/NNTPjsf/web/foo/request.xhtml
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE composition PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<ui:composition xmlns:ui="http://java.sun.com/jsf/facelets"
template="./template.xhtml"
xmlns:h="http://java.sun.com/jsf/html">
<ui:define name="left">
<h:form>
<h:inputText size="2" maxlength="50" value="#{foo.bar}" />
<h:commandButton id="submit" value="submit" action="response" />
</h:form>
</ui:define>
<ui:define name="content">
<h:outputText value="#{foo.bar}"></h:outputText>
</ui:define>
</ui:composition>
thufir#dur:~$
thufir#dur:~$ cat NetBeansProjects/NNTPjsf/web/foo/response.xhtml
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE composition PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<ui:composition xmlns:ui="http://java.sun.com/jsf/facelets"
template="./template.xhtml"
xmlns:h="http://java.sun.com/jsf/html">
<ui:define name="left">
<h:form>
<h:inputText size="2" maxlength="50" value="#{foo.bar}" />
<h:commandButton id="submit" value="submit" action="response" />
</h:form>
</ui:define>
<ui:define name="content">
<h:outputText value="#{foo.bar}"></h:outputText>
</ui:define>
</ui:composition>
thufir#dur:~$
Which I think is ok, in and of itself.
Backing bean:
package guessNumber;
import java.io.Serializable;
import javax.enterprise.context.SessionScoped;
import javax.faces.context.FacesContext;
import javax.inject.Named;
import javax.servlet.http.HttpSession;
#Named
#SessionScoped
public class Foo implements Serializable {
private String bar = "bar";
private String response = "response";
public Foo() {
}
/**
* #return the bar
*/
public String getBar() {
return bar;
}
/**
* #param bar the bar to set
*/
public void setBar(String bar) {
this.bar = bar;
}
/**
* #return the response
*/
public String getResponse() {
FacesContext context = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) context.getExternalContext().getSession(false);
session.invalidate();
response = "hmm";
return response;
}
/**
* #param response the response to set
*/
public void setResponse(String response) {
this.response = response;
}
}
What I would like is just a single client, request_response or something. So that the text input form stays on the left and the result on the right. That's done with composition tags? Or, a third "general client" which has two sub-clients?

You need to change your commandButton on the request page to call an action method in the backing bean:
<h:commandButton id="submit" value="submit" action="#{foo.doAction}" />
In the action method set the response:
public String doAction() {
response = "hmm";
return "response";
}
The return value of the action method navigates to the page /response.xhtml.
But you don't need two pages. You can return null from the action method to reload the current (request) page:
public String doAction() {
response = "hmm";
return null;
}
Then the changed values for bar and response can be shown on the right side:
<ui:define name="content">
<h:outputText value="#{foo.bar}"></h:outputText>
<h:outputText value="#{foo.response}"></h:outputText>
</ui:define>

Related

JSF selectOneRadio function return value as itemValue. For loop to create selectItems

I have 2 questions here for the code below.
The first one is, how can I have an itemValue in selectItem for my selectOneRadio as a return value from a function? I know this is working for a normal itemValue, if I put just "0", it shows up on the next page, but any of the getCaseValueByIndex() returns nothing.
My second question is, instead of listing each selectItem one by one, can i dynamically create them? What I was thinking is creating a function called getCasesCount which would return the size of the cases array (in this case, its 6) and then run a for loop like so:
for (int i = 0; i < casesCount; i++) {
<f:selectItem itemValue="#{CustomBuild.getCaseValueByIndex(i)}" itemLabel="# {CustomBuild.getCaseKey(i)}"/>
}
So then what would happen is that would create the same code I have but dynamically so that If i added or removed items in my LinkedHashMap, the code would reflect those changes rather than crashing for an outofbounds or null pointer error.
index.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:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link href="css/stylesheet.css" rel="stylesheet" type="text/css" />
<title>Jadestar's PC Solutions</title>
</head>
<body>
<h4>Please choose your components.</h4>
<h4>To be eligible for the system builder's discount,
you must select at least <span class ='highlight'> 1 </span> component from each category.</h4>
<br></br>
#{CustomBuild.initialize()}
<h3>Computer Case</h3>
<h:form>
<h:selectOneRadio value="#{CustomBuild.chosenCase}">
<f:selectItem itemValue="#{CustomBuild.getCaseValueByIndex(0)}" itemLabel="#{CustomBuild.getCaseKeyByIndex(0)}"/>
<f:selectItem itemValue="#{CustomBuild.getCaseValueByIndex(1)}" itemLabel="#{CustomBuild.getCaseKeyByIndex(1)}"/>
<f:selectItem itemValue="#{CustomBuild.getCaseValueByIndex(2)}" itemLabel="#{CustomBuild.getCaseKeyByIndex(2)}"/>
<f:selectItem itemValue="#{CustomBuild.getCaseValueByIndex(3)}" itemLabel="#{CustomBuild.getCaseKeyByIndex(3)}"/>
<f:selectItem itemValue="#{CustomBuild.getCaseValueByIndex(4)}" itemLabel="#{CustomBuild.getCaseKeyByIndex(4)}"/>
<f:selectItem itemValue="#{CustomBuild.getCaseValueByIndex(5)}" itemLabel="#{CustomBuild.getCaseKeyByIndex(5)}"/>
</h:selectOneRadio>
<br></br>
<h:commandButton id="submit" value="submit" action="responsePage" />
</h:form>
</body>
</html>
responsePage.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:h="http://xmlns.jcp.org/jsf/html">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link href="css/stylesheet.css" rel="stylesheet" type="text/css" />
<title>Response</title>
</head>
<body>
<h4><h:outputText escape="false" value="#{CustomBuild.chosenCase}"/></h4>
<h:form prependId="false">
<h:commandButton id="backButton" value="Back" action="index" />
</h:form>
</body>
</html>
CustomBuild.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Part1;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;
/**
*
* #author Administrator
*/
#ManagedBean(name = "CustomBuild")
#SessionScoped
public class CustomBuild implements Serializable {
LinkedHashMap <String, String> cases = new LinkedHashMap<String, String>();
String chosenCase;
public String getChosenCase() {
return chosenCase;
}
public void setChosenCase(String chosenCase) {
this.chosenCase = chosenCase;
}
public float getCaseValueByKeyFloat(String key) {
float caseValueByValue = Float.parseFloat(cases.get(key));
return caseValueByValue;
}
public String getCaseKeyByIndex(int index) {
Object newKey = cases.keySet().toArray()[index];
//String tempKey = getCaseValueByIndex(index);
//String newKey = getCaseKeyByValue(tempKey);
return newKey.toString();
}
public String getCaseValueByIndex(int index) {
String caseValue = (new ArrayList<String>(cases.values())).get(index);
return caseValue;
}
public void initialize() {
cases.put("59.95" ,"Eleo 500 $59.95");
cases.put("79.95" ,"Eleo 700 $79.95");
cases.put("99.95" ,"Star Maker $99.95");
cases.put("104.95" ,"Anzooc 1200 $104.95");
cases.put("119.95" ,"Eleo 900 $119.95");
cases.put("139.95" ,"Criticase 1000 $139.95");
}
public CustomBuild() {
System.out.println("Custom Computer");
}
}
You can create an object which holds your key and value pairs.
After that you can use a list of these objects in your bean and use the following code in the xhtmls:
<h:selectOneRadio value="#{CustomBuild.chosenCase}">
<f:selectItems value="#{CustomBuild.getCases}" var="case" itemValue="#{case.value}" itemLabel="#{case.key}" />
</h:selectOneRadio>
Note: if you use an object in selectItem's value, you will need a converter, and to set the proper value you will need a proper equals in your bean.
If you want to stick with the hashmap, here a possible solution for you:
<h:selectOneRadio value="#{CustomBuild.chosenCase}">
<f:selectItems value="#{CustomBuild.cases.keySet()}" var="key" itemValue="#{CustomBuild.getValueByKez(key)}" itemLabel="#{key}" />
</h:selectOneRadio>

Why am I getting this error in my JSF page?

I am trying to search a database that I have developed using JSF as the front end technology. I am getting an error saying the following:
Unable to find method [searchContractors] with [0] parameters
Here is the code that I have used. Can anyone tell me if there is something obvious that I am doing wrong because I can't understand why I am getting this error. Thanks for the help.
JSF code
<!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">
<head>
<title>Search</title>
</head>
<body>
<h:form id="searchForm">
<H2>Search</H2>
<H4>Please select the county that you live in.
</H4>
<table>
<tr>
<td><h:outputLabel for="county">
<h:outputText id="countyLabel" value="County" />
</h:outputLabel></td>
<td><h:selectOneMenu id="countyName"
value="#{searchBean.countyId}">
<f:selectItems value="#{registerBean.counties}" var="county"
itemLabel="#{county.name}" itemValue="#{county.id}" />
</h:selectOneMenu></td>
</tr>
<tr>
<td><h:commandButton id="searchContractors"
action="#{searchBean.searchContractors(searchBean.countyId)}">
<h:outputText value="Search Contractors" />
</table>
</h:form>
</body>
</html>
Java code
#ManagedBean
#SessionScoped
public class SearchBean implements Serializable {
private static final long serialVersionUID = -2107387060867715013L;
private static final String PERSISTENCE_UNIT_NAME = "NeedABuilderUnit";
private static EntityManagerFactory factory;
private int countyId;
public List<BusinessAccount> searchContractors(int countyId) {
factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
EntityManager em = factory.createEntityManager();
List<BusinessAccount> contractorList = new ArrayList<BusinessAccount>();
em.getTransaction().begin();
Query myQuery = em.createQuery("SELECT u FROM BusinessAccount u WHERE u.county.id=:CountyId");
myQuery.setParameter("CountyId", countyId);
contractorList=myQuery.getResultList();
em.getTransaction().commit();
em.close();
return contractorList;
}
public int getCountyId() {
return countyId;
}
public void setCountyId(int countyId) {
this.countyId = countyId;
}
}
the following should work:
<ui:param name="countyId" value="#{searchBean.countyId}" />
...
<h:commandButton id="searchContractors"
action="#{searchBean.searchContractors(countyId)}">

how to send value from commandButton to java bean to change ui

I'm new to jsf.
I'm trying to send value to java bean from commandButton to change src in ui:include and render it with ajax so I when clicked commandButton I could refresh part from the page without load the whole page
and below is my code
\\\\\\\ The Bean File
import javax.enterprise.context.RequestScoped;
import javax.inject.Named;
#Named("urls")
#RequestScoped
public class URLPagesBean
{
private String urlSRC = "";
public String getUrlSRC() {
return urlSRC;
}
public void setUrlSRC(String urlSRC) {
this.urlSRC = urlSRC;
}
public String getURL()
{
String url = "";
if(urlSRC == "page1" || urlSRC == "" || urlSRC == null)
{
url = "page1.xhtml";
}
else if (urlSRC == "page2")
{
url = "page2.xhtml";
}
return url;
}
}
/////////////
The Index file
\\\\\\\\\\\\\\\\\\\\\\
<h:body >
<h:panelGroup layout="block" styleClass="mainContentBox">
<h:panelGroup layout="block" styleClass="mainTopBox">
<h:panelGroup layout="block" styleClass="logoBox"></h:panelGroup>
</h:panelGroup>
<h:form id="subMenuForm">
<h:panelGroup layout="block" styleClass="mainLiftBox">
<h:panelGroup id="msgBoard" layout="block" styleClass="mainMenuButtons">Message Board
<h:panelGroup layout="block" styleClass="subMenuBox">
<h:commandButton id="showMsgBoard" styleClass="subMenuButtonCommand" value="Page1"/>
</h:panelGroup>
</h:panelGroup>
<h:panelGroup layout="block" styleClass="mainMenuButtons">Registrations Book
<h:panelGroup layout="block" styleClass="subMenuBox">
<h:commandButton id="registrInternalApprov" styleClass="subMenuButtonCommand" value="Page2">
<f:ajax render="mainCenterBox" />
</h:commandButton>
</h:panelGroup>
</h:panelGroup>
</h:panelGroup>
<h:panelGroup id="mainCenterBox" styleClass="mainCenterBox" layout="block">
<ui:include id="centerView" src="#{urls.URL}"/>
</h:panelGroup>
</h:form>
</h:panelGroup>
</h:body>
///////////////////////////////////////
page1.xhtml
\\\\\\\\\\\\\\\\\\\\\
<?xml version='1.0' encoding='UTF-8' ?>
<!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:h="http://xmlns.jcp.org/jsf/html"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
<h:head>
<title>Page 1</title>
</h:head>
<h:body>
<ui:fragment>
Page 1
</ui:fragment>
</h:body>
</html>
///////////////////////////
page2.xhtml
\\\\\\\\\\\\\\\\\\\\\
<?xml version='1.0' encoding='UTF-8' ?>
<!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:h="http://xmlns.jcp.org/jsf/html"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
<h:head>
<title>Page 2</title>
</h:head>
<h:body>
<ui:fragment>
Page 2
</ui:fragment>
</h:body>
</html>
///////////////////////////
Use action attribute of h:commandButton like
<h:commandButton value="Submit"
action="#{registrationAction.submitRegistration}" />

How to custom the save button on editor using RichFaces 4?

I am using the RichFaces 4 in my JSF application, but I`d like call a method from my bean when the user press the save button (for example: to save in a file text.txt)
Is there a way to call a java method when the user click on rich:editor save button?
Here is the code i`m using
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!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:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:a4j="http://richfaces.org/a4j"
xmlns:rich="http://richfaces.org/rich">
<h:head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Insert title here</title>
</h:head>
<h:body>
<h:form>
<rich:editor id="editor" toolbar="full" value="#{editorBean.value}"
style="margin-bottom: 1em" height="400" >
<a4j:ajax event="change" render="panel" status="panelUpdateStatus" />
<a4j:ajax event="dirty" render="panel" status="panelUpdateStatus">
<a4j:attachQueue requestDelay="1000" />
</a4j:ajax>
</rich:editor>
<rich:panel id="panel">
<f:facet name="header">
Output from Editor
<a4j:status name="panelUpdateStatus">
<f:facet name="start">
(Updating)
</f:facet>
</a4j:status>
</f:facet>
<h:outputText escape="false" value="#{editorBean.value}" />
</rich:panel>
</h:form>
EditorBean
import java.io.Serializable;
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;
#Named
#SessionScoped
public class EditorBean implements Serializable{
/**
*
*/
private static final long serialVersionUID = 5383915229820571701L;
private String value;
/**
* #return the value
*/
public String getValue() {
return value;
}
/**
* #param value the value to set
*/
public void setValue(String value) {
this.value = value;
}
public void save(){
System.out.println(" Saving ");
//Code to save
}
}
<form>
<editor></editor>
<a4j:commandButton value="Ok" type="submit" execute="#form" action="{editorBean.save()}" />
</form>
Bean:
public void save(){
System.out.println(" Saving: " + this.value);
//Code to save
}
This should submit the form, so the editor value gets saved to the bean.
When pressing the button, the editor content should show in your System.out.

Redirecting form jsf managed bean and showing js alert based on condition in managed bean

Well, in my class Bean
package bean;
import entidade.Usuario;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
/**
*
* #author muky
*/
#ManagedBean
#ViewScoped
public class BeanUsuario {
private Usuario usuario;
public Usuario getUsuario() {
return usuario;
}
public void setUsuario(Usuario usuario) {
this.usuario = usuario;
}
#PostConstruct
public void BeanUsuario() {
if (usuario == null) {
usuario = new Usuario();
}
}
public void verificarUsuario(String login, String senha) {
//UsuarioJpaController usuarioJPA = new UsuarioJpaController();
//usuarioJPA.getEntityManager().createNamedQuery("Usuario.findByLoginSenha").setParameter("login", login).setParameter("senha", senha).getResultList();
}
}
my XHTML
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
<title>Facelet Title</title>
</h:head>
<h:body>
<h:form id="usuario" prependId="false">
<h:panelGrid columns="4" cellpadding="5" style="">
<h:outputLabel for="login" value="Login:" style="font-weight:bold"/>
<p:inputText id="login" value="#{beanUsuario.usuario.login}" />
<h:outputLabel for="senha" value="Senha:" style="font-weight:bold"/>
<p:inputText id="senha" value="#{beanUsuario.usuario.senha}" />
<p:commandButton value="Entrar" ajax="false" actionListener="#{beanUsuario.verificarUsuario(login, senha)}"/>
</h:panelGrid>
</h:form>
</h:body>
</html>
I need to check login and password (senha) if are correct, if yes, they are redirected to other page, else an alert box appears denying access! I'm startin' javaweb and not idea :\
You should pass the values into your beanUsuario.verificarUsuario method (if you really want) like bellow:
#{beanUsuario.verificarUsuario(beanUsuario.usuario.login, beanUsuario.usuario.senha)}"
But I think you dont really need to pass arguments in verificarUsuario method, because you are binding the values of the input text to the managedBean property usuario. So you can simply write the method:
public void verificarUsuario() {
//UsuarioJpaController usuarioJPA = new UsuarioJpaController();
usuarioJPA.getEntityManager().createNamedQuery("Usuario.findByLoginSenha").setParameter("login", usuario.getLogin()).setParameter("senha", usuario.getSenha()).getResultList();
if(canLogin){ //canLogin is the condition to check whether can login or not
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
ec.redirect(ec.getRequestContextPath() + "/home.xhtml");
}
else{
showAlert = true;
}
}
you get the values by only calling usuario.getLogin() and usuario.getSenha() in the method. You put showAlert variable in your managedBean and then in jsf page you can use the <h:outputScript> tag like this:
<h:outputScript rendered="#{beanUsuario.showAlert}">
alert("Invalid login");
</h:outputScript>
Hope this helps you!
it will good if u have a dialog in xhtml page & if you want to show the Dialog just use.
RequestContext requestContext = RequestContext.getCurrentInstance();
requestContext.execute(“dialog.show()”);
& if u want to redirect then use Facescontext redirect("URL") method.
Hope it will help you.

Categories