I'm new to JSF. In my case I want to display several tables (for that purpose I'm using datalist - number of tables will known at runtime) and in each datatable row I need to execute some handler after checkbox has been checked (without any submit button - it will called later).
In code below
<f:ajax listener="#{dataListTry.run(o)}" event="change" render="some_datatable_id"/>
will be called after button have been submitted, but I need to refresh after checkbox will be checked, without submitting button. If I use datatable without datalist, callback calls without any problem.
How can I make callback works in datatable which is in datalist ?
Example of code:
<?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://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:t="http://myfaces.apache.org/tomahawk"
>
<h:body>
<h:form id="some_example_form">
<t:dataList id="some_data_list"
var="dataListTry"
value="#{packageGroups.packageGroupList}" rowIndexVar="pos">
<t:div>
<t:outputLabel title="label"/>
<t:outputText value="Table_#{pos}"/>
</t:div>
<t:selectBooleanCheckbox title="External">
<f:ajax event="change" listener="#{dataListTry.run}" render=":some_example_form"/>
</t:selectBooleanCheckbox>
<t:column>
<t:dataTable id="some_datatable_id"
forceId="true"
forceIdIndex="true"
value="#{dataListTry.packageItems}"
var="o">
<t:column>
<h:outputText value="#{o.prefix}"/>
</t:column>
<t:column defaultSorted="false" sortable="false" width="28px">
<t:selectBooleanCheckbox value="#{o.selected}">
<f:ajax render="some_datatable_id"/>
<f:ajax event="change" listener="#{dataListTry.run(o)}"/>
</t:selectBooleanCheckbox>
</t:column>
</t:dataTable>
</t:column>
</t:dataList>
<br/>
<h:commandButton value="Submit" action="demo" forceId="true"/>
<h:commandButton value="MoveBack" action="demo" forceId="true" actionListener="#{packageGroups.moveBack()}"/>
</h:form>
</h:body>
</html>
And beans are:
PackageItem:
#ManagedBean(name = "packageItem")
#SessionScoped
public class PackageItem {
public boolean selected;
public String prefix;
public PackageItem(String prefix) {
this.prefix = prefix;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
setPrefix("selected after submit");
}
public String getPrefix() {
return prefix;
}
public void setPrefix(String prefix) {
this.prefix = prefix;
}
}
PackageGroup:
#ManagedBean(name = "packageGroup")
#SessionScoped
public class PackageGroup {
private List<PackageItem> packageItems;
private int value;
private String idGroup;
private String resultValue = "Created";
public PackageGroup(String groupId, int groupName, String value, String value2) {
this.idGroup = groupId;
this.value = groupName;
packageItems = new ArrayList<>();
packageItems.add(new PackageItem(value));
packageItems.add(new PackageItem(value2));
}
public PackageGroup() {
}
public List<PackageItem> getPackageItems() {
return packageItems;
}
public void setPackageItems(List<PackageItem> packageItems) {
this.packageItems = packageItems;
}
public void run() {
doClickAction();
}
public void run(PackageItem p) {
doClickAction();
this.resultValue = p.prefix;
}
private void doClickAction() {
packageItems.forEach(e -> e.setPrefix("selected!"));
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
PackageGroups:
#ManagedBean(name = "packageGroups")
#SessionScoped
public class PackageGroups {
private List<PackageGroup> packageGroupList;
public PackageGroups() {
packageGroupList = new ArrayList<>();
packageGroupList.add(new PackageGroup("100", -1, "one", "two"));
packageGroupList.add(new PackageGroup("200", -2, "three", "four"));
}
public void moveBack() {
packageGroupList.clear();
packageGroupList.add(new PackageGroup("100", -1, "one", "two"));
packageGroupList.add(new PackageGroup("200", -2, "three", "four"));
}
public List<PackageGroup> getPackageGroupList() {
return packageGroupList;
}
public void setPackageGroupList(List<PackageGroup> packageGroupList) {
this.packageGroupList = packageGroupList;
}
}
Generated html (only the view - it won't work on stackoverflow):
<?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"><body>
<form id="some_example_form" name="some_example_form" method="post" action="/JavaServerFaces_war_exploded/faces/demo.xhtml" enctype="application/x-www-form-urlencoded">
<input type="hidden" name="some_example_form" value="some_example_form" />
<div><label title="label">
</label>Table_0</div><script type="text/javascript" src="/JavaServerFaces_war_exploded/faces/javax.faces.resource/jsf.js?ln=javax.faces&stage=Development"></script><input id="some_example_form:some_data_list:0:j_idt8" type="checkbox" name="some_example_form:some_data_list:0:j_idt8" value="true" onchange="mojarra.ab('some_example_form:some_data_list:0:j_idt8',event,'change',0,'some_example_form')" title="External" />
<table id="some_datatable_id[0]">
<tbody id="some_datatable_id[0]:tbody_element">
<tr><td>one</td><td width="28px"><input id="some_datatable_id[0]:0:j_idt13" type="checkbox" name="some_datatable_id[0]:0:j_idt13" value="true" onchange="jsf.util.chain(document.getElementById('some_datatable_id[0]:0:j_idt13'), event,'mojarra.ab(\'some_datatable_id[0]:0:j_idt13\',event,\'change\',0,0)', 'mojarra.ab(\'some_datatable_id[0]:0:j_idt13\',event,\'valueChange\',0,\'some_datatable_id[0]\')'); return false;" /></td></tr>
<tr><td>two</td><td width="28px"><input id="some_datatable_id[0]:1:j_idt13" type="checkbox" name="some_datatable_id[0]:1:j_idt13" value="true" onchange="jsf.util.chain(document.getElementById('some_datatable_id[0]:1:j_idt13'), event,'mojarra.ab(\'some_datatable_id[0]:1:j_idt13\',event,\'change\',0,0)', 'mojarra.ab(\'some_datatable_id[0]:1:j_idt13\',event,\'valueChange\',0,\'some_datatable_id[0]\')'); return false;" /></td></tr>
</tbody></table>
<div><label title="label">
</label>Table_1</div><input id="some_example_form:some_data_list:1:j_idt8" type="checkbox" name="some_example_form:some_data_list:1:j_idt8" value="true" onchange="mojarra.ab('some_example_form:some_data_list:1:j_idt8',event,'change',0,'some_example_form')" title="External" />
<table id="some_datatable_id[1]">
<tbody id="some_datatable_id[1]:tbody_element">
<tr><td>three</td><td width="28px"><input id="some_datatable_id[1]:0:j_idt13" type="checkbox" name="some_datatable_id[1]:0:j_idt13" value="true" onchange="jsf.util.chain(document.getElementById('some_datatable_id[1]:0:j_idt13'), event,'mojarra.ab(\'some_datatable_id[1]:0:j_idt13\',event,\'change\',0,0)', 'mojarra.ab(\'some_datatable_id[1]:0:j_idt13\',event,\'valueChange\',0,\'some_datatable_id[1]\')'); return false;" /></td></tr>
<tr><td>four</td><td width="28px"><input id="some_datatable_id[1]:1:j_idt13" type="checkbox" name="some_datatable_id[1]:1:j_idt13" value="true" onchange="jsf.util.chain(document.getElementById('some_datatable_id[1]:1:j_idt13'), event,'mojarra.ab(\'some_datatable_id[1]:1:j_idt13\',event,\'change\',0,0)', 'mojarra.ab(\'some_datatable_id[1]:1:j_idt13\',event,\'valueChange\',0,\'some_datatable_id[1]\')'); return false;" /></td></tr>
</tbody></table>
<br /><input type="submit" name="some_example_form:j_idt15" value="Submit" /><input type="submit" name="some_example_form:j_idt16" value="MoveBack" /><input type="hidden" name="javax.faces.ViewState" id="javax.faces.ViewState" value="-6485444455087447596:-6234064892138587883" autocomplete="off" />
</form></body>
</html>
In posted html view if you check at the checkbutton under Table_% it will execute and change names of other two checkboxes (for example, if you check Table_0 one and two will change their names).
But if you check checkboxes near, for example, one and two, they will change their names only after executing button submit, but I need to get them changed after I clicked on them without
need to call button submit.
Finally found the solution. If forceId and forceIdIndex wouldn't set to true, then the ajax callback works.
This question already has answers here:
How to choose the right bean scope?
(2 answers)
Closed 5 years ago.
When I click on the button I'm getting "record saved" message on another page named "page1.html" as mentioned in JSF faces configuration file, but the record is null for string and 0 for integers. Where am I getting wrong?
my managed bean code(Inventory.java):-
import java.awt.Frame;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import javax.inject.Named;
import javax.enterprise.context.Dependent;
import javax.swing.JOptionPane;
/**
*
* #author Pritam
*/
#Named(value = "inventory")
#Dependent
public class Inventory {
String item;
int price, qty;
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public int getQty() {
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}
public Inventory() {
}
public String addItem()
{
try{
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection con=DriverManager.getConnection("jdbc:derby://localhost:1527/practice");
Statement ps=con.createStatement();
ps.executeUpdate("insert into inv_table values('"+getItem()+"',"+getPrice()+","+getQty()+")");
return "Success";
}
catch(Exception e){
return "Failed";
}
}
}
this is my jsf page(MyIndex.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:f="http://xmlns.jcp.org/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
<title>Facelet Title</title>
</h:head>
<h:body>
<h:form>
<pre>
Item Name: <h:inputText id="t1" value="#{inventory.item}" size="10">
</h:inputText>
Item Price: <h:inputText id="t2" value="#{inventory.price}" size="10">
<f:convertNumber type="number"></f:convertNumber>
</h:inputText>
Item Quantity: <h:inputText id="t3" value="#{inventory.qty}" size="10">
<f:convertNumber type="number"></f:convertNumber>
</h:inputText>
<h:commandButton id="btn" value="add item" action="#{inventory.addItem()}">
</h:commandButton>
</pre>
</h:form>
</h:body>
</html>
JSF faces configuration file:-
<?xml version='1.0' encoding='UTF-8'?>
<faces-config version="2.2"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd">
<navigation-rule>
<from-view-id>MyIndex.xhtml</from-view-id>
<navigation-case>
<from-action>#{inventory.addItem()}</from-action>
<from-outcome>Success</from-outcome>
<to-view-id>page1.html</to-view-id>
</navigation-case>
<navigation-case>
<from-action>#{inventory.addItem()}</from-action>
<from-outcome>Failed</from-outcome>
<to-view-id>page2.html</to-view-id>
</navigation-case>
</navigation-rule>
</faces-config>
try your codes with binding="" instead of value=""
Item Name: <h:inputText id="t1" binding="#{inventory.item}" size="10">
</h:inputText>
Item Price: <h:inputText id="t2" binding="#{inventory.price}" size="10">
<f:convertNumber type="number"></f:convertNumber>
</h:inputText>
Item Quantity: <h:inputText id="t3" binding="#{inventory.qty}" size="10">
<f:convertNumber type="number"></f:convertNumber>
</h:inputText>
I using spring security+JSF+primefaces
in custom login, i put a command button
but command button no workin ...
and when in p:commandbutton ----------> ajax="false" ---------> is work!
and when used f:ajax in jsf(core) --------> no work
and i use in spring security.xml file :
test.xhtml ----> jsf(core) --------> no work
<?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://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core"
xml:lang="en" lang="en">
<head>
<title>faces-request</title>
</head>
<body>
<h:form>
<center>
<h:outputText id="outtxt" value="#{authentiocationBean.ajaxTest}"/><br/>
<h:inputText id="intxt" value="#{authentiocationBean.ajaxTest}"/><br/>
<h:commandButton value="Submit">
<f:ajax execute="intxt" render="outtxt"/>
</h:commandButton>
</center>
</h:form>
</body>
</html>
Spring_security.xml:
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.2.xsd">
<http auto-config="true" use-expressions="true">
<intercept-url pattern="/Admin/*" access="hasRole('ROLE_ADMIN')"/>
<intercept-url pattern="/user/*" access="hasAnyRole('ROLE_USER,ROLE_ADMIN')"/>
<form-login login-page="/login.xhtml"
authentication-failure-url="/Fail.xhtml?error"/>
<logout logout-url="/j_spring_security_logout" delete-cookies="JSESSIONID,SPRING_SECURITY_REMEMBER_ME_COOKIE"
invalidate-session="true"
logout-success-url="/login.xhtml"/>
<session-management session-authentication-error-url="/401.xhtml" session-fixation-protection="migrateSession">
<concurrency-control max-sessions="1" expired-url="/login.xhtml"/>
</session-management>
<remember-me key="myAppKey"/>
<access-denied-handler error-page="/AccDe.xhtml"/>
<headers>
<xss-protection/>
<frame-options/>
<cache-control/>
<content-type-options/>
</headers>
<csrf/>
</http>
<authentication-manager alias="authenticationManager">
<authentication-provider>
<jdbc-user-service data-source-ref="myDataSource"
users-by-username-query="select username, password, active from users where username=?"
authorities-by-username-query="select us.username, ur.authority from users us, user_roles ur
where us.user_id = ur.user_id and us.username =? "
/>
<password-encoder ref="passwordEncoder" hash="sha-256"/>
</authentication-provider>
</authentication-manager>
<bean id="passwordEncoder"
xmlns="http://www.springframework.org/schema/beans"
class="org.springframework.security.authentication.encoding.ShaPasswordEncoder">
<!--org.springframework.security.crypto.password.PasswordEncoder for salt!-->
<constructor-arg value="256"/>
</bean>
</beans:beans>
LoginPage:
<?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://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui">
<h:head>
<title>faces-request</title>
</h:head>
<h:body>
<h:form prependId="false" id="formLogin">
<center>
<p:panelGrid style="border-width: 0px;" columns="2">
UserName:
<p:inputText required="true" id="j_username"/>
Password:
<p:password required="true" id="j_password"/>
</p:panelGrid>
<p:commandButton type="submit" id="login" action="#{authentiocationBean.doLogin()}" value="Login"/>
<p:outputLabel for="_spring_security_remember_me" value="Remember me: "/>
<p:selectBooleanCheckbox id="_spring_security_remember_me"/>
<br/>
</center>
</h:form>
</h:body>
</html>
AuthentiocationBean class
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import java.io.IOException;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
/**
* #author Admin
*/
#RequestScoped
#ManagedBean
public class AuthentiocationBean {
public String ajaxTest = "Test";
boolean isLogged = false;
public String role = "ROLE_ADMIN";
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String name = auth.getName();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String doLogin() throws IOException, ServletException {
isLogged = true;
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext context = facesContext.getExternalContext();
RequestDispatcher dispatcher = ((ServletRequest) context.getRequest()).getRequestDispatcher("/j_spring_security_check");
dispatcher.forward((ServletRequest) context.getRequest(), (ServletResponse) context.getResponse());
FacesContext.getCurrentInstance().responseComplete();
// It's OK to return null here because Faces is just going to exit.
return null;
}
public void doLogout() {
// FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
// return "/logout.xhtml";
// return null;
}
public boolean isLogged() {
return isLogged;
}
public void setLogged(boolean logged) {
isLogged = logged;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public String getAjaxTest() {
return ajaxTest;
}
public void setAjaxTest(String ajaxTest) {
this.ajaxTest = ajaxTest;
}
}
thanks
It's just a login page, so why bother with AJAX?
I have integrated Spring 3.1.4 LDAP support with JSF. Although I initially wrote a custom authentication bean, I do not use it any longer. I am not expert, and I'm sure there's a different way from what I implemented.
(1) Simple login page (excerpt):
<h:inputText id="j_username"/>
<h:inputText type="password" id="j_password" value=""/>
<h:commandButton name="submit" type="submit" value="Log In" />
<input type="reset" value="Reset" />
(2.1) In web.xml, I declare a context-param to name the security configuration file (mentioned in step 3 below).
I also declare the Spring security filter chain, which you can read about here:
http://docs.spring.io/spring-security/site/docs/3.1.4.RELEASE/reference/security-filter-chain.html#filter-chains-with-ns
(2.2) In faces-config I declare:
<el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
(2.3) In faces-config, I declare a custom UserSession bean with session scope.
UserSession bean has this method:
#PostConstruct
public void loadAuthorities() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
. . .
. . .
}
(3) UserSession bean is referred to from within the landing page (menu.xhtml) which is declared in my security config file (declared in web.xml in step 2.1 above):
<security:form-login default-target-url="/menu.xhtml" always-use-default-target="true" authentication-failure-url="/denied.xhtml" />
<security:logout invalidate-session="true" delete-cookies="JSESSIONID" logout-url="/j_spring_security_logout" />
(4) User is authenticated then redirected to menu.xhtml
Menu.xhtml causes UserSession bean to load.
UserSession bean pulls a list of Authorities from the SecurityContext.
UserSession bean provides simple wrappers to check whether a user has authority to view pages and resources:
public boolean isRole(String role) {
return authorities.contains((String) role);
}
public boolean roleContains(String s);
public boolean roleEndsWith(String s);
. . .
. . .
I have 2 pages, inputForm.xhtml and outputPage.xhtml.
In inputForm.xhtml, there are 1 textfield and 1 checkbox. When user clicks submit button, the values are passed to outputPage.xhtml in URL.
The value of textfield can be passed correctly. However, no matter the checkbox is checked or not, the parameter in URL is always false.
e.g. http://localhost:8080/jsf-web/outputPage.xhtml?c=false&n=franz
I am using myFaces 2.1.13. I really have no idea how to fix that. Thanks.
inputForm.xhtml
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html">
<f:metadata>
<f:viewParam name="n" value="#{inputFormBean.name}" />
<f:viewParam name="c" value="#{inputFormBean.nameUppercase}" />
</f:metadata>
<h:head>
</h:head>
<h:body>
<h:form>
<p>Name: <h:inputText value="#{inputFormBean.name}" /></p>
<p>Name uppercase: <h:selectBooleanCheckbox value="#{inputFormBean.nameUppercase}"/></p>
<p><h:commandButton action="output_page" value="Submit" /></p>
</h:form>
</h:body>
</html>
outputPage.xhtml
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html">
<f:metadata>
<f:viewParam name="n" value="#{outputPageBean.name}" />
<f:viewParam name="c" value="#{outputPageBean.nameUppercase}" />
</f:metadata>
<h:head>
</h:head>
<h:body>
<h3>Welcome #{outputPageBean.nameUppercase ? outputPageBean.name.toUpperCase() : outputPageBean.name}!!</h3>
</h:body>
</html>
faces-config.xml
<?xml version="1.0"?>
<faces-config xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
version="2.0">
<navigation-rule>
<from-view-id>*</from-view-id>
<navigation-case>
<from-outcome>output_page</from-outcome>
<to-view-id>/outputPage.xhtml</to-view-id>
<redirect include-view-params="true"/>
</navigation-case>
</navigation-rule>
</faces-config>
InputFormBean.java
package com.franzwong.jsfweb;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
#ManagedBean
#RequestScoped
public class InputFormBean {
private String name;
private boolean nameUppercase;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isNameUppercase() {
return nameUppercase;
}
public void setNameUppercase(boolean nameUppercase) {
this.nameUppercase = nameUppercase;
}
}
OutputPageBean.java
package com.franzwong.jsfweb;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
#ManagedBean
#RequestScoped
public class OutputPageBean {
private String name;
private boolean nameUppercase;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isNameUppercase() {
return nameUppercase;
}
public void setNameUppercase(boolean nameUppercase) {
this.nameUppercase = nameUppercase;
}
}
Finally I tried primitive int and it is passed as 0 no matter what value I input.
Therefore, I tried Boolean, Integer and found that the value I input can be passed correctly in URL.
I have a commandButton in JSF 2.0 with a actionvalue that I want to call a method in a bean and otherwise do nothing. However when I click on it, it redirects to the previous page.
This was programmed in java 1.7 in eclipse using glassfish 3.1.1.
Here is the code for the welcome.xhtml file where the commandButton is (showDetails) but there are many other files, so I have included a link to a WAR file so it is possible to check everything out. If i change the action attribute to point to a method that does not exist I will not get an error, I will again be redirected to the frontpage.
The program is started from the index.html file. After importing remember to leftclick on the project, go to properties>project facets and tick of JavaServerFaces 2.0
The relevant code:
welcome.xhtml
<?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">
<h:head>
<title>Insert title here</title>
</h:head>
<h:body>
<h3>#{userBean.user.name}</h3>
<hr />
<form>
<h:commandButton value="Back" action="index" />
</form>
<form>
<h:commandButton value="Show details" action="#{userBean.changeRenderDetails}" />
<h:panelGrid rendered="#{userBean.renderDetails}" columns="2">
<h:outputText value="Brugernavn:" /> #{userBean.user.name}
<h:outputText value="Password:" /> #{userBean.user.password}
</h:panelGrid>
</form>
</h:body>
</html>
userBean
package model;
import java.io.Serializable;
import javax.enterprise.context.SessionScoped;
import javax.inject.Inject;
import javax.inject.Named;
#Named("userBean")
// or #ManagedBean(name="user")
#SessionScoped
public class UserBean implements Serializable {
// Oprettes når en bean oprettes
private User user = new User("", "");
#Inject
// Det nuværende service objekt initialiseres automatisk
private Service service;
public String validateUser() {
return service.validateUser(user);
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
//Lektion 10 - opg1
private boolean renderDetails;
public void changeRenderDetails(){
setRenderDetails(!isRenderDetails());
}
public boolean isRenderDetails() {
return renderDetails;
}
public void setRenderDetails(boolean renderDetails) {
this.renderDetails = renderDetails;
}
}
and the user class
package model;
public class User {
private String name;
private String password;
public User(String name, String password) {
super();
this.name = name;
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
navigation rules, none of which should have anything to do with the button which redirects to index.html:
<?xml version="1.0" encoding="UTF-8"?>
<faces-config
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee /web-facesconfig_2_0.xsd"
version="2.0">
<navigation-rule>
<from-view-id>/index.xhtml</from-view-id>
<navigation-case>
<from-outcome>success</from-outcome>
<to-view-id>/welcome.xhtml</to-view-id>
</navigation-case>
<navigation-case>
<from-outcome>failure</from-outcome>
<to-view-id>/error.xhtml</to-view-id>
</navigation-case>
</navigation-rule>
</faces-config>
As shown in every decent JSF book/tutorial, you should be using <h:form> instead of <form>.
<h:form>
<h:commandButton value="Back" action="index" />
</h:form>
<h:form>
<h:commandButton value="Show details" action="#{userBean.changeRenderDetails}" />
<h:panelGrid rendered="#{userBean.renderDetails}" columns="2">
<h:outputText value="Brugernavn:" /> #{userBean.user.name}
<h:outputText value="Password:" /> #{userBean.user.password}
</h:panelGrid>
</h:form>
See also
commandButton/commandLink/ajax action/listener method not invoked or input value not set/updated #1