f:validateRequiered doesn't work as expected - jsf-2

I have just created a NetBeans project with JSF 2.0 and I have a problem with f:validateRequired. The bean
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
#ManagedBean
#RequestScoped
public class TestBean {
private String value;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String action() {
return "test";
}
}
and the page
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.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>Test</title>
<h:outputStylesheet name="css/stylesheet.css" />
</h:head>
<h:body>
<h:form>
<div id="content">
Value:
<h:message for="test" />
<h:inputText value="#{testBean.value}" id="test">
<f:validateRequired />
</h:inputText>
<br/>
<h:commandButton action="#{testBean.action}" value="Action" />
</div>
</h:form>
</h:body>
</html>
seems to be allright, but the h:message isn't there until I supply the requered="true" attribute on the inputText. What I am missing? Why the validation does not occure whithout the requered="true" attribute?

I figured the answer: fields with empty input are not validated at all by default. If you wish to validate such field you have to set required=true. See UIInput.validateValue() JavaDoc
You can enable the validation of empty fields by setting the javax.faces.VALIDATE_EMPTY_FIELDS context parameter to true. See JavaDoc. After doing that the example above works as expected.

I know this post is kind of old, but I'm using MyFaces and apparently javax.faces.VALIDATE_EMPTY_FIELDS is set to false by default.

Related

Pass param from one jsf page to another

I want to pass selectedExamId from chooseexam page to exam page, what is the good way to do that? is it a good practice to use two baking bean for single jsf page?
One more thing is I am getting same Question list each time?
I have following jsf page
chooseExam.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 lang="en"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
</h:head>
<h:body>
<ui:composition template="/templates/admin/template.xhtml">
<ui:define name="content">
<h:selectOneRadio value="#{examBean.selectedExamId}">
<f:selectItems value="#{chooseExamBean.exams}" var="exam" itemValue="#{exam.examId}" itemLabel="#{exam.examName}"/>
</h:selectOneRadio>
<h:commandButton value="Submit" action="/user/exam?faces-redirect=true"/>
</ui:define>
</ui:composition>
</h:body>
</html>
and
exam.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 lang="en"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
</h:head>
<h:body>
<ui:composition template="/templates/admin/template.xhtml">
<ui:define name="content">
<ui:repeat value="#{examBean.questions}" var="question">
<h:outputLabel value="#{question.question}"/>
<h:selectOneRadio value="#{examBean.questionAnswerMap[question]}">
<f:selectItem itemValue="#{question.choice1}" itemLabel="#{question.choice1}"/>
<f:selectItem itemValue="#{question.choice2}" itemLabel="#{question.choice2}"/>
<f:selectItem itemValue="#{question.choice3}" itemLabel="#{question.choice3}"/>
<f:selectItem itemValue="#{question.choice4}" itemLabel="#{question.choice4}"/>
</h:selectOneRadio>
</ui:repeat>
<h:commandButton value="Submit" action="#{examBean.calculate}"/>
</ui:define>
</ui:composition>
</h:body>
</html>
following are the backing beans
ChooseExamBean.java
#Component
#ManagedBean
public class ChooseExamBean {
List<Exam> exams;
#Autowired
private ExamService examService;
#PostConstruct
public void init(){
exams = examService.getAllExams();
}
public List<Exam> getExams() {
return exams;
}
public void setExams(List<Exam> exams) {
this.exams = exams;
}
}
and
ExamBean.java
#Component
#ManagedBean
public class ExamBean {
private List<Question> questions;
private Map<Question, String> questionAnswerMap = new HashMap<>();
private int score;
private Long selectedExamId;
#Autowired
private QuestionService questionService;
#PostConstruct
public void init() {
if(selectedExamId != null)
questions = questionService.getQuestionsForExam(selectedExamId);
}
public Map<Question, String> getQuestionAnswerMap() {
return questionAnswerMap;
}
public void setQuestionAnswerMap(Map<Question, String> questionAnswerMap) {
this.questionAnswerMap = questionAnswerMap;
}
public List<Question> getQuestions() {
if(questions == null)
questions = questionService.getQuestionsForExam(selectedExamId);
return questions;
}
public void setQuestions(List<Question> questions) {
this.questions = questions;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public Long getSelectedExamId() {
return selectedExamId;
}
public void setSelectedExamId(Long selectedExamId) {
this.selectedExamId = selectedExamId;
}
public String calculate() {
score = questionAnswerMap.size();
return "result?faces-redirect=true";
}
}
Since you are using a RequestScope Beans for the (ExamBean and the ChooseExamBean) you cant keep the values after the response , so you should user the viewParam tag to pass the value from the first page to the second page.
you should make something like the following :
1- the ChooseExam.jsf , you have your radioButtons that will save its value in the chooseExamBean :
<f:view xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html">
<html xmlns="http://www.w3.org/1999/xhtml">
<h:head></h:head>
<h:body>
<h:form>
<h:selectOneRadio label="examType" value="#{chooseExamBean.examNumber}">
<f:selectItem itemLabel="exam1" itemValue="1"/>
<f:selectItem itemLabel="exam2" itemValue="2"/>
</h:selectOneRadio>
<h:commandButton value="commandButton1" action="#{chooseExamBean.navigateToExamPage}" />
</h:form>
</h:body>
</html>
</f:view>
2- in the action of the commandButton you will call a method in the bean to navigate , before navigation you will append a param to the url like the following in the navigateToExamPage method :
#ManagedBean(name = "chooseExamBean")
#RequestScoped
public class ChooseExamBean {
public ChooseExamBean() {
super();
}
private String examNumber;
public void setExamNumber(String examNumber) {
this.examNumber = examNumber;
}
public String getExamNumber() {
return examNumber;
}
public Object navigateToExamPage() {
return "exam?faces-redirect=true&examId="+getExamNumber();
}
}
3- in the exam.jsf page , you have to get the value of the parameter , here you will use the tag like the following :
<f:view xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html">
<html xmlns="http://www.w3.org/1999/xhtml">
<h:head></h:head>
<h:body>
<h:form>
<f:metadata>
<f:viewParam name="examId" value="#{examBean.examNumber}"/>
<f:event type="preRenderView" listener="#{examBean.onLoad}" />
</f:metadata>
<h:outputText value="#{examBean.examNumber}"/>
</h:form>
</h:body>
</html>
</f:view>
the view param have to attributes :
1- name :which is the name of the parameter that you want to get from the url.
2- value :which is where you want to set the value of the parameter.
so in our case the name is "examId" and we want to set the value in "examBean.examNumber" .
here you will find a problem if you didnt use tag , because you want to get the examId onPage Load in the postConstrct method , but the f:param will be called after the postConstruct , so we have to use the like the following :
<f:event type="preRenderView" listener="#{examBean.onLoad}" />
this will help us to perform custom task before a JSF page is displayed.
4- in you examBean :
#ManagedBean(name = "examBean")
#RequestScoped
public class ExamBean {
public ExamBean() {
super();
}
private String examNumber;
public void setExamNumber(String examNumber) {
this.examNumber = examNumber;
}
public String getExamNumber() {
return examNumber;
}
public void onLoad () {
System.out.println("onLoad = "+getExamNumber());
}
}
Please use this with your requirements and everything will go smooth.
Please refer to the following answer here, here and here .
Hope that Helps.

a4j:ajax keyup event not working

After a long time I'm using a4j:ajax to get simple text from h:inputText and render to h:outputText but it's not working
I found many examples like this but none of them worked for me.
this id my bean
import javax.faces.bean.*;
#ManagedBean(name="usertest")
#RequestScoped
public class UserBean {
private String name = "john";
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
and this is my index.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"
xmlns:a4j="http://richfaces.org/a4j"
xmlns:rich="http://richfaces.org/rich">
<h:head>
</h:head>
<body>
<h:form id="f1">
<h:inputText id="name1" value="#{usertest.name}">
<a4j:ajax event="keyup" render="name2" execute="#form"></a4j:ajax>
</h:inputText>
<h:outputText id="name2" value="#{usertest.name}"></h:outputText>
</h:form>
</body>
</html>
I'm using JSF 2.0 and RichFaces 4.0
Any solution would help me.
Tanks

JSF Message on SUBMIT action

I begin with my case:
JSF 2.1
Tomcat 7.0.27
Netbeans as IDE
JSF and PRIMEFace (but optional)
Level JSF beginner
Level JAVA good and not god
I have done a simple JSF site to learn how to works with JSF. My question is based on Login example at this step the problem is not related about that login that is obviously insicure.
A bit of code:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
/**
*
* #author
*/
#ManagedBean
#SessionScoped
//#RequestScoped
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private final String userName = "User";
private final String userPassword = "12345";
private String name;
private String password;
private boolean isLogged=false;
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;
}
public String login() {
if( !(userName==null || password==null)
&&
(userName.equals( name ) && userPassword.equals( password ))) {
isLogged=false;
return "main";
} else {
isLogged=true;
return "index";
}
}
public boolean getIsLogged(){
return isLogged;
}
}
The page index
<?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">
<h:head>
<title>TSAM 7.5 Login</title>
</h:head>
<h:body>
Login system
<br />
<!--<h:link outcome="welcomePrimefaces" value="Primefaces welcome page" />-->
<h:form>
User : <h:inputText value="#{user.name}" />
Password : <h:inputSecret value="#{user.password}" />
<h:commandButton action="#{user.login()}" value="Submit" />
<h:commandButton value="reset" type="reset" />
<h:commandButton value="otherpage" action="otherpage"></h:commandButton>
</h:form>
</h:body>
</html>
The main page
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.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:p="http://primefaces.org/ui">
<f:event type="preRenderView" listener="#{user.isLogged}"/>
<f:view contentType="text/html">
<h:head>
<f:facet name="first">
<meta content='text/html; charset=UTF-8' http-equiv="Content-Type"/>
<title>PrimeFaces</title>
</f:facet>
</h:head>
<h:body>
<p:layout fullPage="true">
<p:layoutUnit position="north" size="100" resizable="true" closable="true" collapsible="true">
Header
</p:layoutUnit>
<p:layoutUnit position="south" size="100" closable="true" collapsible="true">
Footer
</p:layoutUnit>
<p:layoutUnit position="west" size="175" header="Left" collapsible="true">
<p:menu>
<p:submenu label="Resources">
<p:menuitem value="Demo" url="http://www.primefaces.org/showcase-labs/ui/home.jsf" />
<p:menuitem value="Documentation" url="http://www.primefaces.org/documentation.html" />
<p:menuitem value="Forum" url="http://forum.primefaces.org/" />
<p:menuitem value="Themes" url="http://www.primefaces.org/themes.html" />
</p:submenu>
</p:menu>
</p:layoutUnit>
<p:layoutUnit position="center">
Welcome to PrimeFaces
</p:layoutUnit>
</p:layout>
</h:body>
</f:view>
</html>
First
I use action="#{user.login()}" to make navigation action is this correct or there is a better pattern?
But the real question is: How to show a message If I redirect?
I like to show a message I know the example by PrimeFace http://www.primefaces.org/showcase/ui/dialogLogin.jsf. but it doesn't redirect or show anything.
But if i use only "plain" JSW without PrimeFace, i like to put a
because it is similar to PrimeFaces so switch is simple.
I'd like to adopt a "pattern" so i can reuse it for eg when i do a serch an no data is present, or when i call "erease DB" and application say work in progress an then say OK all bank account are esreased (Only an example!! but interesting because there are 2 message).
Thanks
I try
public String login() {
if (!(userName == null || password == null)
&& (userName.equals( name ) && userPassword.equals( password ))) {
isLogged = true;
return "main";
} else {
isLogged = false;
FacesMessage facesMsg;
facesMsg = new FacesMessage( FacesMessage.SEVERITY_ERROR, "No login", "No login because username or passsword are incorrect etc" );
FacesContext fc = FacesContext.getCurrentInstance();
fc.addMessage( "loginError", facesMsg );
return "index";
}
}
And edited the page
<h:body>
Login system
<br />
<!--<h:link outcome="welcomePrimefaces" value="Primefaces welcome page" />-->
<h:form>
User : <h:inputText value="#{user.name}" />
Password : <h:inputSecret value="#{user.password}" />
<h:commandButton action="#{user.login()}" value="Submit" />
<h:commandButton value="reset" type="reset" />
<h:commandButton value="Cambio Password" action="changePassword"></h:commandButton>
</h:form>
<h:message for="" style="color:red;margin:8px;"/>
</h:body>
It works but it's not ok because it's not ok to put a string in the bean. And I need the multilanguage this string has to generated by the beans.... mmm this is not OK something i'm missing.
There's extremely a lot of noise in the question. I understand that your question ultimately boils down to:
How do I create a localized faces message in bean action method?
In that case, just get the message from the current resource bundle yourself.
As you're talking about localization, you should surely already have something like as
<resource-bundle>
<base-name>com.example.i18n.text</base-name>
<var>text</var>
</resource-bundle>
in your faces-config.xml. You could just get it in the bean as well with help of ResourceBundle which JSF itself is actually also using under the covers
Locale locale = FacesContext.getCurrentInstance().getViewRoot().getLocale();
ResourceBundle text = ResourceBundle.getBundle("com.example.i18n.text", locale);
This way you could compose your message as
String summary = text.getString("messages.no_login_summary");
String detail = text.getString("messages.no_login_detail");
new FacesMessage(FacesMessage.SEVERITY_ERROR, summary, detail);

Form doesn't submit values when commandLink is used instead of commandButton

I made following jsf page. In my Managed Bean i want evaluate the input,
but i dont get the values.
If i press my commandLink i dont get any values. when i use a commandButton it works:
<?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:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<ui:composition template="../templates/common.xhtml">
<ui:define name="pageTitle">Test</ui:define>
<ui:define name="pageHeader">Test</ui:define>
<ui:define name="body">
<h:panelGroup id="messagePanel" layout="block">
<h:messages errorStyle="color: red" infoStyle="color: green"
layout="table" />
</h:panelGroup>
<h:form>
<h:outputLabel value="#{bundle.SearchAdressLabel_name}"
for="axname" />
<h:inputText id="axname"
value="#tbaxController.name}"
title="#{bundle.SearchAdressTitle_name}" />
</h:panelGrid>
<br />
<br />
<h:commandButton id="submit" value="#{bundle.SearchAdressLabel_cmdsearch}" action="#{tbaxController.prepareList}">
</h:commandButton>
<h:commandLink action="#{tbaxController.prepareList}"
value="#{bundle.SearchAdressLabel_cmdsearch}" immediate="true" />
<br />
<br />
<h:commandLink value="#{bundle.SearchAdressLabel_cmdclear}"
type="reset" />
</h:form>
</ui:define>
</ui:composition>
</html>
Here is a part of my MB:
#ManagedBean(name = "tbaxController")
#SessionScoped
public class tbaxController implements Serializable {
private static final long serialVersionUID = 1L;
private static final org.apache.log4j.Logger logger = org.apache.log4j.Logger
.getLogger(tbaxController.class);
private Tbax current;
private DataModel items = null;
#EJB
private TbaxFacade ejbFacade;
private PaginationHelper pagination;
private int selectedItemIndex;
private String name;
public tbaxController() {
}
public String getname() {
// Get the field
return searchAxart;
}
public void setname(String oname) {
// Set the field this.searchAxart
this.name = oname.trim();
}
...
public String prepareList() {
logger.info("prepareList:" + name); **//null with commandLink!
recreateModel();
return "ADList";
}
...
Why does my prepareList method doesn't get any values with a commandLink?
The immediate="true" makes jsf to step over the process validation and update model phases. It jump directly to invoke application phase. That's why you don't get any values on the model. Try removing it and see what happens.

Spring Web flow with JSF evaluation

I am new to Spring Web flow.
This is my code.
main-flow.xml
<?xml version="1.0" encoding="UTF-8"?>
<flow xmlns="http://www.springframework.org/schema/webflow"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/webflow
http://www.springframework.org/schema/webflow/spring-webflow-2.0.xsd">
<var name="hello" class="org.springframework.webflow.samples.booking.hello"/>
<view-state id="hello">
<transition on="click" to="test"></transition>
</view-state>
<action-state id="test">
<evaluate expression="hello.saytest()">
</evaluate>
<transition on="yes" to="page1" ></transition>
<transition on="no" to="page2"></transition>
</action-state>
<view-state id="page1"></view-state>
<view-state id="page2"></view-state>
</flow>
Hello.java
package org.springframework.webflow.samples.booking;
import java.io.Serializable;
public class hello implements Serializable {
String name;
/**
*
*/
#Override
public String toString() {
return "hello [name=" + name + "]";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private static final long serialVersionUID = 1L;
public boolean saytest() {
System.out.println(name);
String test = "new";
if (name == test) {
return true;
} else {
return false;
}
}
}
hello.xhtml
<!DOCTYPE composition PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<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"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui"
template="/WEB-INF/layouts/standard.xhtml">
<ui:define name="notes">
<p>
Check the calendar widget and the tooltips on the credit card fields.
The form uses Ajax-based validations to redisplay server-side errors without refreshing the entire page.
The booking bean backing the form is a flow-scoped object (see <strong>booking-flow.xml</strong>).
</p>
</ui:define>
<ui:define name="content">
<h:form>
<h:outputLabel for="price">Enter the Name:</h:outputLabel>
<h:inputText id="name" value="#{hello.name}">
</h:inputText>
<p:commandButton id="click" action="click" value="click" />
</h:form>
</ui:define>
</ui:composition>
Here I am trying to get some value from hello.xhtml and try to evaluate it in main-flow.xml.
If the value which i tried is new then it have to navigate to page1 or it have to take it to page2.xhtml.Now I my case even i enter new in inputtext box it take to me to page2 only.
Can anyone help me.
Change
if (name == test)
to
if (name.equals(test))
Or, simply,
if (name.equals("new"))
See http://www.javabeginner.com/learn-java/java-string-comparison

Resources