This question already has an answer here:
Primefaces selectonemenu displaying data outside the input [duplicate]
(1 answer)
Closed 6 years ago.
I am trying to build a web app that involves a drop down menu which, upon selecting an option, populates a table with data. I had issues, and so tried to isolate the problem by trying to recreate the following example from the Primefaces website. I am having the following problems:
1) The selectOneMenu produces a textbox right above it in the resulting page.
2) The seelctOneMenu also produces a bulleted list of the options that are already on that select menu.
3) The ajax listener on the first select menu does not update the second menu, and does not seem to run any method in the DropdownView class.
In a nutshell, the output is unexpected, especially since I am more or less copy/pasting example code.
I am running this all on JDeveloper12c with Weblogic, JSF 2.2 and Primefaces 6.0.
Here is the code I am running, almost all of which is copy/pasted from the Primefaces site
Here's my dropdown.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://xmlns.jcp.org/jsf/facelets"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:p="http://primefaces.org/ui">
<body>
<h:form>
<h:messages errorStyle="color:red" />
<p:growl id="msgs" showDetail="true" />
<p:panel header="Select a Location" style="margin-bottom:10px;">
<h:panelGrid columns="2" cellpadding="5">
<p:outputLabel for="country" value="Country: " />
<p:selectOneMenu id="country" value="#{dropdownView.country}" style="width:150px">
<p:ajax listener="#{dropdownView.onCountryChange()}" update="city" />
<f:selectItem itemLabel="Select Country" itemValue="" noSelectionOption="true" />
<f:selectItems value="#{dropdownView.countries}" />
</p:selectOneMenu>
<p:outputLabel for="city" value="City: " />
<p:selectOneMenu id="city" value="#{dropdownView.city}" style="width:150px">
<f:selectItem itemLabel="Select City" itemValue="" noSelectionOption="true" />
<f:selectItems value="#{dropdownView.cities}" />
</p:selectOneMenu>
</h:panelGrid>
<p:separator />
<p:commandButton value="Submit" update="msgs" actionListener="#{dropdownView.displayLocation()}" icon="ui-icon-check" />
</p:panel>
</h:form>
</body>
</html>
My DropdownView.java, which is the same code from the example site:
package test;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
#ManagedBean
#ViewScoped
public class DropdownView implements Serializable {
private Map<String,Map<String,String>> data = new HashMap<String, Map<String,String>>();
private String country;
private String city;
private Map<String,String> countries;
private Map<String,String> cities;
#PostConstruct
public void init() {
countries = new HashMap<String, String>();
countries.put("USA", "USA");
countries.put("Germany", "Germany");
countries.put("Brazil", "Brazil");
Map<String,String> map = new HashMap<String, String>();
map.put("New York", "New York");
map.put("San Francisco", "San Francisco");
map.put("Denver", "Denver");
data.put("USA", map);
map = new HashMap<String, String>();
map.put("Berlin", "Berlin");
map.put("Munich", "Munich");
map.put("Frankfurt", "Frankfurt");
data.put("Germany", map);
map = new HashMap<String, String>();
map.put("Sao Paolo", "Sao Paolo");
map.put("Rio de Janerio", "Rio de Janerio");
map.put("Salvador", "Salvador");
data.put("Brazil", map);
}
public Map<String, Map<String, String>> getData() {
return data;
}
public void setData(Map<String, Map<String, String>> data) {
this.data = data;
}
public void setCountries(Map<String, String> countries) {
this.countries = countries;
}
public void setCities(Map<String, String> cities) {
this.cities = cities;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public Map<String, String> getCountries() {
return countries;
}
public Map<String, String> getCities() {
return cities;
}
public void onCountryChange() {
if(country !=null && !country.equals(""))
cities = data.get(country);
else
cities = new HashMap<String, String>();
}
public void displayLocation() {
FacesMessage msg;
if(city != null && country != null)
msg = new FacesMessage("Selected", city + " of " + country);
else
msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Invalid", "City is not selected.");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
}
Here is my web.xml:
<?xml version = '1.0' encoding = 'windows-1252'?>
<web-app 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-app_3_0.xsd"
version="3.0">
<servlet>
<servlet-name>FacesServlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>FacesServlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>FacesServlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>FacesServlet</servlet-name>
<url-pattern>*.jsf</url-pattern>
</servlet-mapping>
</web-app>
Here is my faces-config.xml:
<faces-config 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"
version="2.2">
</faces-config>
Replace the HTML <body> tag by the JSF <h:body> tag. Probably even more important, add an <h:head /> line. It may be empty, but it's important because that's where the JavaScript and CSS files are added.
BTW, the problems you describe indicate that these files are missing. You see how the selectOneMenu is constructed from the HTML building blocks, but without the CSS and JavaScript glue code.
Related
While the view can get all values from the bean, when a checkbox (h:selectBooleanCheckbox) is toggled the bean is not updated. The setSelected() method in Item is never called from the view.
I've tried changing the scope of the bean to application, using a map instead of a value for the selected property and a foolish attempt at writing my own ajax javascript function.
The application I'm working with is a bit legacy so I'm using Tomcat 6, JSF 1.2 and Richfaces 3.3.3.Final.
It seems like it should be simple, I think I'm missing something obvious, but I've been at this for two days and can't figure out why the bean isn't updated.
My view is:
<!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:c="http://java.sun.com/jstl/core"
xmlns:fn="http://java.sun.com/jsp/jstl/functions"
xmlns:a4j="http://richfaces.org/a4j"
xmlns:rich="http://richfaces.org/rich">
<head>
<title>JSF</title>
</head>
<body>
<h:form id="tableForm">
<rich:dataTable id="table" value="#{managedBean}" var="item" width="100%">
<rich:column label="Select" align="center" width="40px" >
<f:facet name="header">
<h:outputText value="Select" />
</f:facet>
<h:selectBooleanCheckbox value="#{item.selected}" >
<a4j:support execute="#this" event="onclick" ajaxSingle="true"/>
</h:selectBooleanCheckbox>
</rich:column>
<rich:column label="Name" align="center" width="40px">
<f:facet name="header">
<h:outputText value="Name" />
</f:facet>
<h:outputText value="#{item.name}" />
</rich:column>
</rich:dataTable>
</h:form>
</body>
</html>
I have a managed bean ItemBean in session scope:
import org.richfaces.model.ExtendedTableDataModel;
public class ItemBean extends ExtendedTableDataModel<Item>{
public ItemBean() {super(new ItemProvider());}
}
ItemProvider is:
import org.richfaces.model.DataProvider;
public class ItemProvider implements DataProvider<Item>{
private List<Item> items = new ArrayList<Item>();
public ItemProvider(){
for(int i = 0; i < 10; i++){
items.add(new Item(i, "Item "+i));
}
}
public Item getItemByKey(Object key) {return items.get((Integer)key);}
public List<Item> getItemsByRange(int fromIndex, int toIndex) {
return new ArrayList<Item>(items.subList(fromIndex, toIndex));
}
public Object getKey(Item arg0) {return arg0.getId();}
public int getRowCount() {return items.size();}
}
and Items are:
public class Item {
private final int id;
private final String name;
private boolean selected;
public Item(int id, String name) {
this.id = id;
this.name = name;
selected = false;
}
public int getId(){
return id;
}
public String getName(){
return name;
}
public boolean isSelected(){
return selected;
}
public void setSelected(boolean selected){
this.selected = selected;
}
}
I would assume, that your vanilla html, head and body tags might cause this.
Ajax-stuff (javascript) sometimes has to go into the <head> section of the page (along with required script references). Because JSF is working with components, it needs to insert the javascript required for a certain component at the time the component is added to the underlaying Object-Model.
Therefore JSF itself needs to manage the html, head and body tags.
So, instead of creating them as vanilla-html, use the proper<h:html>, <h:body> and <h:head> tags, which will handover this task to JSF. This way, the required javascript code for your onclick-event handler should be generated and the checkbox should work as expected.
The issue was that I hadn't set up my web.xml properly.
I was missing the following which routes the request to richfaces:
<filter>
<display-name>RichFaces Filter</display-name>
<filter-name>richfaces</filter-name>
<filter-class>org.ajax4jsf.Filter</filter-class>
</filter>
<filter-mapping>
<filter-name>richfaces</filter-name>
<servlet-name>Faces Servlet</servlet-name>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
<dispatcher>INCLUDE</dispatcher>
</filter-mapping>
I'm trying to use Bean validation instead of JSF validation since it is a more DRY aproach, i'm using the annotations on my model but when i insert null data on jsf fields it does nothing...
None of the annotations that i'm using is having any effect, its like they are not there....
I'm using Tomcat 8
My 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>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Insert title here</title>
</h:head>
<h:body>
<h1>Cadastro de funcionario</h1>
<h:form>
<h:messages/>
<h:panelGrid columns="3">
<h:outputLabel value="Salário: R$ " for="campo-salario"/>
<h:inputText id="campo-salario" value="#{funcionarioBean.funcionario.salario}">
<f:convertNumber locale="pt_BR"/>
</h:inputText>
<h:message for="campo-salario" />
<h:outputLabel value="Código: " for="campo-codigo"/>
<h:inputText id="campo-codigo" value="#{funcionarioBean.funcionario.codigo}"/>
<h:message for="campo-codigo"/>
<h:outputLabel value="Data: " for="campo-aniversario"/>
<h:inputText id="campo-aniversario" value="#{funcionarioBean.funcionario.aniversario}">
<f:convertDateTime pattern="dd/MM/yyyy" />
</h:inputText>
<h:message for="campo-aniversario"/>
<h:commandButton value="Cadastrar" action="#{funcionarioBean.mensagem}"/>
</h:panelGrid>
</h:form>
</h:body>
</html>
My Bean
#ManagedBean
public class FuncionarioBean {
private Funcionario funcionario = new Funcionario();
public void mensagem(){
System.out.println("Pressionado");
}
public Funcionario getFuncionario() {
return funcionario;
}
public void setFuncionario(Funcionario funcionario) {
this.funcionario = funcionario;
}
}
My Funcionario class
import java.util.Date;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
public class Funcionario {
#NotNull(message="{br.com.k19.Funcionario.nome")
#Min(value = 0)
private Double salario;
#NotNull
#Min(value = 5)
#Max(value = 19)
private Integer codigo;
#NotNull
private Date aniversario;
public Double getSalario() {
return salario;
}
public void setSalario(Double salario) {
this.salario = salario;
}
public Integer getCodigo() {
return codigo;
}
public void setCodigo(Integer codigo) {
this.codigo = codigo;
}
public Date getAniversario() {
return aniversario;
}
public void setAniversario(Date aniversario) {
this.aniversario = aniversario;
}
}
My lib
Can't post pictures yet.
Lib
>
antlr-2.7.7.jar
dom4j-1.6.1.jar
hibernate-commons-annotations-4.0.5.Final.jar
hibernate-core-4.3.6.Final.jar
hibernate-jpa-2.1-api-1.0.0.Final.jar
hibernate-validator-5.0.0.final.jar
jandex-1.1.0.Final.jar
javassist-3.18.1-GA.jar
javax.servlet.jsp.jstl-1.2.1.jar
javax.servlet.jsp.jstl-api-1.2.1.jar
jboss-logging-3.1.3.GA.jar
jboss-logging-annotations-1.2.0.Beta1.jar
jboss-transaction-api_1.2_spec-1.0.0.Final.jar
jsf-api-2.2.8.jar
jsf-impl-2.2.8.jar
mysql-connector-java-5.1.23.bin.jar
omnifaces-1.8.1.jar
primefaces-5.0.jar
validation-api-1.0.0.GA.jar
My web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
<display-name>K19-Conversao-e-Validacao</display-name>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<context-param>
<param-name>com.sun.faces.writeStateAtFormEnd</param-name>
<param-value>false</param-value>
</context-param>
<context-param>
<param-name>javax.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL</param-name>
<param-value>true</param-value>
</context-param>
</web-app>
Downloaded hibernate jars again to match the versions
Download validator: http://hibernate.org/validator/
Download ORM: http://hibernate.org/orm/
My lib
Working as intend now
ref: Bean Validation #NotNull, #NotBlank and #NotEmpty does not work in JSF+Tomcat
In RichFaces, inorder to upload a file I used rich:fileUpload. By using rich:fileUpload Add, Upload and Clear All buttons are automatically generating in the richfaces livedemo example but for me Add, Upload and Clear All are appearing as text in my browser where should I change so that Add,upload and clearAll can be clickable. Do I have to change any settings in web.xml / pom.xml file.
I am using RichFaces 4 and JSF 2.
This is my web.xml :
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 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-app_2_5.xsd">
<display-name>Sample RichFaces 4 Application</display-name>
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<context-param>
<param-name>javax.faces.SKIP_COMMENTS</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>org.richfaces.skin</param-name>
<param-value>#{skinBean.skin}</param-value>
</context-param>
<context-param>
<param-name>org.richfaces.fileUpload.maxRequestSize</param-name>
<param-value>1000000000</param-value>
</context-param>
<context-param>
<param-name>org.richfaces.fileUpload.createTempFiles</param-name>
<param-value>true</param-value>
</context-param>
<listener>
<listener-class>com.sun.faces.config.ConfigureListener</listener-class>
</listener>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.jsf</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
<mime-mapping>
<extension>ecss</extension>
<mime-type>text/css</mime-type>
</mime-mapping>
<welcome-file-list>
<welcome-file>index.jsf</welcome-file>
</welcome-file-list>
<login-config>
<auth-method>BASIC</auth-method>
</login-config>
Hi, i am getting those add and update buttons now correctly by simply providing h:head and h:body tags but i am getting this exception javax.faces.event.AbortProcessingException and files are not being uploaded as shown in the example provided in the link "FileUpload example".Can anyone plz help me out from this issue
This is my xhtml page
<!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">
<ui:composition>
<h:head>
<h:outputStylesheet>
.top {
vertical-align: top;
}
.info {
height: 202px;
overflow: auto;
}
</h:outputStylesheet>
</h:head>
<h:body>
<h:form>
<h:panelGrid columns="2" columnClasses="top,top">
<rich:fileUpload fileUploadListener="#{fileUploadBean.listener}" id="upload" acceptedTypes="jpg, gif, png, bmp"
ontyperejected="alert('Only JPG, GIF, PNG and BMP files are accepted');" maxFilesQuantity="5">
<a4j:ajax event="uploadcomplete" execute="#none" render="info" />
</rich:fileUpload>
<h:panelGrid id="info" layout="block">
<rich:panel bodyClass="info">
<f:facet name="header">
<h:outputText value="Uploaded Files Info" />
</f:facet>
<h:outputText value="No files currently uploaded" rendered="#{fileUploadBean.size==0}" />
<rich:dataGrid columns="1" value="#{fileUploadBean.files}" var="file" rowKeyVar="row">
<rich:panel bodyClass="rich-laguna-panel-no-header">
<h:panelGrid columns="2">
<a4j:mediaOutput element="img" mimeType="image/jpeg" createContent="#{fileUploadBean.paint}"
value="#{row}" style="width:100px; height:100px;" cacheable="false">
<f:param value="#{fileUploadBean.timeStamp}" name="time" />
</a4j:mediaOutput>
<h:panelGrid columns="2">
<h:outputText value="File Name:" />
<h:outputText value="#{file.name}" />
<h:outputText value="File Length(bytes):" />
<h:outputText value="#{file.length}" />
</h:panelGrid>
</h:panelGrid>
</rich:panel>
</rich:dataGrid>
</rich:panel>
<br/>
<a4j:commandButton action="#{fileUploadBean.clearUploadData}" render="info, upload" value="Clear Uploaded Data"
rendered="#{fileUploadBean.size>0}" />
</h:panelGrid>
</h:panelGrid>
</h:form>
</h:body>
</ui:composition>
</html>
This is my FileUploadBean Class
package com.acc.upload;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import com.acc.fileupload.utils.FileUploadEvent;
import com.acc.fileupload.utils.UploadedFile;
#ManagedBean(name = "fileUploadBean")
#SessionScoped
public class FileUploadBean{
private ArrayList<File> files = new ArrayList<File>();
private int uploadsAvailable = 5;
private boolean autoUpload = false;
private boolean useFlash = true;
public int getSize() {
if (getFiles().size()>0){
return getFiles().size();
}else
{
return 0;
}
}
public FileUploadBean() {
}
public void paint(OutputStream stream, Object object) throws IOException {
stream.write(getFiles().get((Integer)object).getData());
}
public void listener(FileUploadEvent event) throws Exception{
UploadedFile item = event.getUploadedFile();
File file = new File();
file.setLength(item.getData().length);
file.setName(item.getName());
file.setData(item.getData());
files.add(file);
uploadsAvailable--;
}
public String clearUploadData() {
files.clear();
setUploadsAvailable(5);
return null;
}
public long getTimeStamp(){
return System.currentTimeMillis();
}
public ArrayList<File> getFiles() {
return files;
}
public void setFiles(ArrayList<File> files) {
this.files = files;
}
public int getUploadsAvailable() {
return uploadsAvailable;
}
public void setUploadsAvailable(int uploadsAvailable) {
this.uploadsAvailable = uploadsAvailable;
}
public boolean isAutoUpload() {
return autoUpload;
}
public void setAutoUpload(boolean autoUpload) {
this.autoUpload = autoUpload;
}
public boolean isUseFlash() {
return useFlash;
}
public void setUseFlash(boolean useFlash) {
this.useFlash = useFlash;
}
}
File Class
package com.acc.upload;
public class File {
private String Name;
private String mime;
private long length;
private byte[] data;
public byte[] getData() {
return data;
}
public void setData(byte[] data) {
this.data = data;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
int extDot = name.lastIndexOf('.');
if(extDot > 0){
String extension = name.substring(extDot +1);
if("png".equals(extension)){
mime="image/png";
}else {
mime = "img/unknown";
}
}
}
public long getLength() {
return length;
}
public void setLength(long length) {
this.length = length;
}
public String getMime(){
return mime;
}
}
Thanks a lot.Now that error is gone for me .
I set the createTemp files to true in web.xml but i am unable to find the uploaded file in the temp folder in my local system.And also is it possible to store the uploaded file to a desired location in our local system by changing any settings in web.xml file ?
Please help in these two issues.
Regarding your buttons icons problem, I'm pretty sure you don't manage yourself the skin of RichFaces, so you can remove this from your web.xml :
<context-param>
<param-name>org.richfaces.skin</param-name>
<param-value>#{skinBean.skin}</param-value>
</context-param>
RichFaces will now use the default skin option.
According to your comment, you where missing h:head which is mandatory in order to include necessary resources CSS and JavaScript for RichFaces.
Moreover, your last problem is related to your imports that are bad :
import com.acc.fileupload.utils.FileUploadEvent;
import com.acc.fileupload.utils.UploadedFile;
should be replaced for :
import org.richfaces.event.FileUploadEvent;
import org.richfaces.model.UploadedFile;
Other info :
The example you are based on is from RichFaces 3.3.3 (this is shown in the footer). Double check your view code with this example for RichFaces 4.3.2.
I also get this problem with richface 4.0.0 and spring 4. When upload the file I alway get this error message "Request prolog cannot be read".
And I solved this problem by: set multipart resolever to
instead of CommonsMultipartResolver
for DispatcherServlet. Because the CommonsMultipartResolver of spring is not consistent with richface 4.0.0
Hope this help!
i am facing a validation error when submitting a form with cascading SelectOneMenu : when i use a sessionscoped for my bean it's work, but for requestscoped parametre it's not ok and i got the famous validation error. and for my application constraints i need to use the requestscoped .
here is my bean
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
#ManagedBean(name="pprBean")
#RequestScoped
public class PPRBean implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String city;
private String suburb;
private UIInput sourceMenu;
private Map<String,String> cities = new HashMap<String, String>();
private Map<String,Map<String,String>> suburbsData = new HashMap<String, Map<String,String>>();
private Map<String,String> suburbs = new HashMap<String, String>();
public UIInput getSourceMenu() {
return sourceMenu;
}
public void setSourceMenu(UIInput sourceMenu) {
this.sourceMenu = sourceMenu;
}
public PPRBean() {
cities.put("Istanbul", "Istanbul");
cities.put("Ankara", "Ankara");
cities.put("Izmir", "Izmir");
Map<String,String> suburbsIstanbul = new HashMap<String, String>();
suburbsIstanbul.put("Kadikoy", "Kadikoy");
suburbsIstanbul.put("Levent", "Levent");
suburbsIstanbul.put("Cengelkoy", "Cengelkoy");
Map<String,String> suburbsAnkara = new HashMap<String, String>();
suburbsAnkara.put("Kecioren", "Kecioren");
suburbsAnkara.put("Cankaya", "Cankaya");
suburbsAnkara.put("Yenimahalle", "Yenimahalle");
Map<String,String> suburbsIzmir = new HashMap<String, String>();
suburbsIzmir.put("Cesme", "Cesme");
suburbsIzmir.put("Gumuldur", "Gumuldur");
suburbsIzmir.put("Foca", "Foca");
suburbsData.put("Istanbul", suburbsIstanbul);
suburbsData.put("Ankara", suburbsAnkara);
suburbsData.put("Izmir", suburbsIzmir);
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getSuburb() {
return suburb;
}
public void setSuburb(String suburb) {
this.suburb = suburb;
}
public Map<String, String> getCities() {
return cities;
}
public void setCities(Map<String, String> cities) {
this.cities = cities;
}
public Map<String, Map<String, String>> getSuburbsData() {
return suburbsData;
}
public void setSuburbsData(Map<String, Map<String, String>> suburbsData) {
this.suburbsData = suburbsData;
}
public Map<String, String> getSuburbs() {
return suburbs;
}
public void setSuburbs(Map<String, String> suburbs) {
this.suburbs = suburbs;
}
public void handleCityChange() {
if(city !=null && !city.equals(""))
suburbs = suburbsData.get(city);
else
suburbs = new HashMap<String, String>();
}
public String Connexion() {
return "success";
}
}
my form page :
<?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:p="http://primefaces.org/ui">
<h:head>
</h:head>
<body class="box_center" >
<h:form id="form">
<p:growl id="msgs" showDetail="true"/>
<p:panel header="Double Combo" style="margin-bottom:10px;">
<h:panelGrid columns="2" cellpadding="5">
<p:selectOneMenu id="city" value="#{pprBean.city}">
<f:selectItem itemLabel="Select City" itemValue="" />
<f:selectItems value="#{pprBean.cities}" />
<p:ajax update="suburbs"
listener="#{pprBean.handleCityChange}" />
</p:selectOneMenu>
<p:selectOneMenu id="suburbs" value="#{pprBean.suburb}" >
<f:selectItem itemLabel="Select Suburb" itemValue="" />
<f:selectItems value="#{pprBean.suburbs}" />
</p:selectOneMenu>
</h:panelGrid>
<p:separator />
<h:commandLink action="#{pprBean.Connexion()}" >
Connexion
</h:commandLink>
</p:panel>
</h:form>
</body>
</html>
my result page :
<?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:p="http://primefaces.org/ui">
<h:head>
</h:head>
<body class="box_center" >
<h:form id="form">
<p:growl id="msgs" showDetail="true"/>
pprBean.city : <h:outputText value="#{pprBean.city}"/>
pprBean.suburb : <h:outputText value="#{pprBean.suburb}"/>
</h:form>
</body>
</html>
my faces-config file:
<?xml version='1.0' encoding='UTF-8'?>
<!-- =========== FULL CONFIGURATION FILE ================================== -->
<faces-config version="2.0"
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">
<navigation-rule>
<from-view-id>/index.xhtml</from-view-id>
<navigation-case>
<from-action>#{pprBean.Connexion()}</from-action>
<from-outcome>success</from-outcome>
<to-view-id>/resultat.xhtml</to-view-id>
</navigation-case>
</navigation-rule>
</faces-config>
please any help.
This question already has answers here:
Avoid back button on JSF web application
(2 answers)
Closed 1 year ago.
I'm having an issue with the back button, not keeping data in a dynamic dropdown in JSF on a request scoped bean.
I have a form with 2 dropdowns where dropdown2 is dynamic based on what is selected in dropdown1. Below is my code for these dropdowns.
<h:selectOneMenu id="group" label="group" value="#{queryBacking.groupInternalId}">
<f:ajax event="valueChange" render="membership" />
<f:selectItems value="#{supportBean.groupInstitutions}" var="group" itemValue="#{group.institutionInternalId}" itemLabel="#{group.institutionName}" />
</h:selectOneMenu>
<h:selectOneMenu id="membership" label="Membership" value="#{queryBacking.institutionInternalId}">
<f:selectItem itemLabel="Select One" itemValue="0" />
<f:selectItems value="#{queryBacking.groupMembershipInstitutions}" var="institution" itemValue="#{institution.institutionInternalId}" itemLabel="#{institution.institutionShortName}" />
</h:selectOneMenu>
My code works great except that if you submit the form and then click the back button, dropdown2 does not contain any values. How can fix this issue?
You mean the back button in the browser right?
The browser probably loads the page out of the browser cache. So you need to disable caching with a filter:
public class NoCacheFilter implements Filter {
private FilterConfig config;
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpReq = (HttpServletRequest) request;
HttpServletResponse httpRes = (HttpServletResponse) response;
if (!httpReq.getRequestURI().startsWith(
httpReq.getContextPath() + ResourceHandler.RESOURCE_IDENTIFIER)) {
httpRes.setHeader("Cache-Control",
"no-cache, no-store, must-revalidate"); // HTTP 1.1.
httpRes.setHeader("Pragma", "no-cache"); // HTTP 1.0.
httpRes.setDateHeader("Expires", 0); // Proxies.
}
chain.doFilter(request, response);
}
#Override
public void destroy() {
config = null;
}
#Override
public void init(FilterConfig config) throws ServletException {
this.config = config;
}
}
And then add this to the web.xml:
<filter>
<filter-name>NoCacheFilter</filter-name>
<filter-class>yourpackage.NoCacheFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>NoCacheFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
You can specify the pages you want filtered in <url-pattern> </url-pattern>
You can initialize the values for the page in the bean constructor:
TestBean class
#ManagedBean
#ViewScope
public class TestBean {
private String name;
public TestBean() {
//initialize the name attribute
//recover the value from session
HttpSession session = (HttpSession)FacesContext.getCurrentInstance()
.getExternalContext().getSession(false);
name = session.getAttribute("name");
if (name == null) {
name = "Luiggi";
}
}
public String someAction() {
//save the value in session
HttpSession session = (HttpSession)FacesContext.getCurrentInstance()
.getExternalContext().getSession(false);
session.setAttribute("name", name);
return "Test";
}
//getters and setters...
}
Test.xhtml
<ui:composition
xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html">
<h:body>
<h:outputText value="Hello " />
<h:outputText value="#{testBean.name}" />
<h:form>
<h:outputText value="Write your name: " />
<h:inputText value="#{testBean.name}" />
<br />
<h:commandButton value="Change name" action="#{testBean.someAction}" />
</h:form>
</h:body>
</ui:composition>
Adding an example to remove the session attribute before navigating to Text.xhtml
SomeBean class
#ManagedBean
#RequestScope
public class SomeBean {
public SomeBean() {
}
public String gotoTest() {
//removes an item from session
HttpSession session = (HttpSession)FacesContext.getCurrentInstance()
.getExternalContext().getSession(false);
session.removeAttribute("name");
return "Test";
}
}
SomeBean.xhtml
<ui:composition
xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html">
<h:body>
<h:form>
<!-- Every time you navigate through here, your "name"
session attribute will be removed. When you hit the back
button to get Test.xhtml you will see the "name"
session attribute that is actually stored. -->
<h:commandButton value="Go to Test" action="#{someBean.gotoTest}" />
</h:form>
</h:body>
</ui:composition>