To get Validation Messages from the Controller - validation

I am using JSF 2.This is my controller.
package com.acc.validations;
import java.io.Serializable;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
#ManagedBean(name="user")
#SessionScoped
public class Controller implements Serializable{
private static final long serialVersionUID = 1L;
String name;
String 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;
}
private String checkUser(String name,String password) {
if(("admin".equalsIgnoreCase(name)) && ("admin".equalsIgnoreCase(password))){
return "result";
}else{
/*System.out.println("Enter Valid details");*/
FacesMessage msg = new FacesMessage("Authentication Failed.","Authentication Failed");
msg.setSeverity(FacesMessage.SEVERITY_ERROR);
return null;
}
}
public void execute(){
checkUser(name, password);
}
}
This is my XHTML 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" >
<h:body>
<h1>Custom validator in JSF 2.0</h1>
<h:form >
<h:panelGrid columns="3">
User Name:
<h:inputText id="username" value="#{user.name}"
required="true" >
<f:validateLength minimum="4" maximum="15" />
</h:inputText>
<h:message for="username" style="color:red" />
Password :
<h:inputSecret id="password" value="#{user.password}"
required="true" >
<f:validator validatorId="com.acc.validations.PasswordValidator" />
</h:inputSecret>
</h:panelGrid>
<h:commandButton value="Submit" action="#{user.execute}" />
</h:form>
</h:body>
</html>
My Requirement is that if the user enters user name and password as "admin" the control should redirect to result.xhtml else it should display message in the facesContext that i had written in the contoller.
This is my result.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://java.sun.com/jsf/html">
<h:body>
<h1>Custom validator in JSF 2.0</h1>
<h:panelGrid columns="2">
Welcome to User :
<h:outputText value="#{user.name}" />
</h:panelGrid>
</h:body>
</html>
I am not able to render the result.xhtml eventhough i enter admin as username and password and also i am not getting any messages while i am entering wrong credentials.And also i am not getting any errors.Could u please help me in this regard in order to work as per my requirement.

Have you tried something like this :
In your .xhtml
<p:inputText id="j_username" required="true" value="#{login.nomLogin}" />
In your "controller"
#ManagedBean(name="login")
#SessionScoped
public class LoginBean implements Serializable {
private String nomLogin;
private Boolean isConnected = false;
//Getter and Setter for this one
public String checkValidUser(){
//To see the value of login
System.out.println("Login a pour valeur :"+ getNomLogin());
if((getNomLogin().equals("admin")== true){
isConnected =true;
return "ok";
}}}
This is how my login works, you can do the same thing with a boolean it depend of what you need.
I think you can test the value, if you have something like that :
you can potentially test the valor of this , for example my menu is hidden if anybody is connected and show if admin is connected :
<p:panel id="HidePanel" header="Menu caché" rendered="#{login.isConnected == 'true'}" />

Related

f:ajax does not render the outputPanel until I refresh

Every time I debug the application and type something in the Textbox, the Controller remember only when I refresh the page.
Without the ajax Tag it's working fine. So my guess: the rendering of the outputPanel does not Work. I set Breakpoints (ajax listener and field setter are both called) and tested it many times and the outcome was the controller only works when i clicked the button and then refreshed the page. Referring JSF, I work with Eclipse for Java EE and Tomcat v.9.0 and earlier.
Strange thing is that the execute attribute only has the id for the name input in its execute attribute and still the listener is called (sysout is printed), this is not to be expected accordimg to #9 in commandButton/commandLink/ajax action/listener method not invoked or input value not set/updated. But changing it to #form does not change it
new.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://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>
<h:form id="formID">
<h:inputText id="name" value="#{LayoutController.name}"></h:inputText>
<h:commandButton value="Welcome Me">
<f:ajax event="click" listener="#{LayoutController.listen}" execute=":formID:name" render=":formID:output"/>
</h:commandButton>
<h:panelGroup id="output">
<h:outputText value="#{LayoutController.name}"/>
</h:panelGroup>
</h:form>
</h:body>
</html>
LayoutController.java:
package Template;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.event.AjaxBehaviorEvent;
#ManagedBean(name="LayoutController")
#SessionScoped
public class LayoutController{
private String name;
public LayoutController() {
this.name="";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void listen (AjaxBehaviorEvent event) {
this.name = this.name + " ! ";
System.out.println("Clicked");
}
}

Why is this ajax #form submit not updating and rendering model values? [duplicate]

This question already has answers here:
commandButton/commandLink/ajax action/listener method not invoked or input value not set/updated
(12 answers)
Closed 5 years ago.
I have the following scenario and a problem with a form submit using ajax:
<?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"
xmlns:ui="http://java.sun.com/jsf/facelets">
<h:head>
<h:outputStylesheet library="css" name="employee.css" />
<title>Welcome</title>
</h:head>
<h:body>
<h:form>
<h:panelGrid>
<h:outputLabel for="first_name" value="First Name" />
<h:inputText id="first_name"
value="#{employeeController.model.firstName}" required="true" />
<h:outputLabel for="last_name" value="Last Name" />
<h:inputText id="last_name"
value="#{employeeController.model.lastName}" required="true" />
<h:outputLabel for="email" value="Email" />
<h:inputText id="email" value="#{employeeController.model.email}"
required="true" />
<h:outputLabel for="phone_number" value="Phone" />
<h:inputText id="phone_number"
value="#{employeeController.model.phoneNumber}" required="true" />
<h:outputLabel for="salaray" value="Salary" />
<h:inputText id="salaray" value="#{employeeController.model.salary}"
required="true" />
<h:commandButton value="Save(AJAX)">
<f:ajax execute="#form" render="modelOutput"/>
</h:commandButton>
</h:panelGrid>
</h:form>
<h:panelGrid id="modelOutput">
<h:outputText id="fName"
value="First Name: #{employeeController.model.firstName}" />
<h:outputText value="Last Name: #{employeeController.model.lastName}" />
<h:outputText value="E-Mail: #{employeeController.model.email}" />
<h:outputText
value="Phonenumber: #{employeeController.model.phoneNumber}" />
<h:outputText value="Salary: #{employeeController.model.salary}" />
</h:panelGrid>
</h:body>
</html>
The model is a simple javabean with just getter and setter for the values.
When I click on the ajax Button I can see a request going to the server, holding my Form-Data.
I get a partial-response back with the hard-coded values for the outputtexts - but not with the model values.
I can see that also my setters are not called.
If I change the ajax execute to a specific inputText component id - than it works for that one.
What am I missing?
--
EmployeeBean
public class EmployeeBean {
private String firstName;
private String lastName;
private String email;
private String phoneNumber;
private Float salary;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public Float getSalary() {
return salary;
}
public void setSalary(Float salary) {
this.salary = salary;
}
}
EmployeeController:
#ManagedBean
#RequestScoped
public class EmployeeController {
private EmployeeBean model;
#PostConstruct
public void init() {
model = new EmployeeBean();
}
public EmployeeBean getModel() {
return model;
}
public void clearAjax(AjaxBehaviorEvent ajaxBehaviorEvent) {
clearUiAreaForm(ajaxBehaviorEvent.getComponent());
System.out.println("Form cleared");
}
}
So I found the reason and the solution.
The main problem is following:
From a lifecycle listener I saw that the processing on server side skipped phases 4 & 5.
What is the reason for this?
Well - phase 3 is about validation. My form had some validation restrictions, i.e. required.
I did not fill out all the input fields and therefor validation phase was not successfull. JSF then skips Phase 4 & 5 - now we also know why the setters were not called.
Here comes the kicker:
It fails completely silently!
You do get a good ajax request containing the form parameters. And you do get a good partial-response - but without dynamic values from the bean.
There was no error message in the application log (well, there should also be none but this leads you to knowing there was no exception).
But apparently Ajax does not fill any component like it is done when you use a full page request.
You do not have any information about the failing validation.
If you do not use a lifecycle information output than you can't see it in any way.
Additionally, the only thing I was able to find out is adding a component that renders some information. Add a hardcoded outputText that will only be rendered on the information of facesContext.validationFailed and render it by ajax facelet.
<h:commandButton value="Save (AJAX)">
<f:ajax execute="#form" render="modelOutput global_flag_validation_failed_render" />
</h:commandButton>
<h:messages />
<h:panelGroup id="global_flag_validation_failed_render">
<h:outputText id="global_flag_validation_failed" value="Fehler in Ajax aufgetreten!"
rendered="#{facesContext.validationFailed}" />
</h:panelGroup>
I have no idea if this is the specified and wanted behaviour of Mojarra 2.2.14 - does anybody know it?

init method with annotation PostConstruct create error

I wrote a method 'init' with annotation PostConstruct
#ManagedBean
#ViewScoped
public class BrandController {
#ManagedProperty(value="#{carsService}")
private CarsService carsService;
private String name;
private String country;
private List<Brand> listBrands;
public BrandController() {
}
public void setListBrands(List<Brand> listBrands) {
this.listBrands = listBrands;
}
#PostConstruct
public void init()
{
setListBrands(carsService.listBrand());
}
//here is all setters and getters
}
I have also
public interface CarsService
{
public void createBrand(Brand b);
public void deleteBrand(Brand b);
public List<Brand> listBrand();
}
and implementation for this interface
#Service("carsService")
#Transactional
public class CarSeviceImpl implements CarsService{
#Autowired
private BrandDao branDao;
public BrandDao getBranDao() {
return branDao;
}
public void setBranDao(BrandDao branDao) {
this.branDao = branDao;
}
#Override
public List<Brand> listBrand()
{
return branDao.listBrand();
}
#Override
public void createBrand(Brand b) {
branDao.createBrand(b);
}
#Override
public void deleteBrand(Brand b) {
branDao.deleteBrand(b);
}
}
my brand.xhtml view:
<?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:p="http://primefaces.org/ui">
<h:head>
<title>brands</title>
</h:head>
<h:body>
<h:form id="formBrands">
<p:growl/>
<h:panelGrid columns="2" cellpadding="6">
<p:outputLabel value="Name" for="nameIn"/>
<p:inputText value="#{brandController.name}" required="true" requiredMessage="the input field name is empty" id="nameIn"/>
<p:outputLabel value="Coutry" for="countryIn"/>
<p:inputText value="#{brandController.country}" required="true" requiredMessage="the input field coutry is empty" id="countryIn"/>
<p:commandButton value="save" action="#{brandController.save}" update=":formBrands :formList"/>
</h:panelGrid>
</h:form>
<h:form id="formList">
<p:dataTable id="brandTable" value="#{brandController.listBrands}" var="brand" rowKey="#{brand.name}" rows="10"
emptyMessage="there is no brands" paginator="true" paginatorPosition="bottom">
<p:column headerText="name">
<h:outputText value="#{brand.name}"/>
</p:column>
<p:column headerText="country">
<h:outputText value="#{brand.country}"/>
</p:column>
</p:dataTable>
</h:form>
</h:body>
I`m getting error like this '
An error occurred performing resource injection on managed bean
brandController
' when I try run my webapp with brand view...
Could you tell me where I am doing something wrong ?

Why is this Ajax Call not Working?

Trying to use an ajax request to render a label without refreshing the entire page. So far every time I click the command button the whole page refreshes still and I can't seem to figure out what I am doing wrong.
Search By Title..
<h:commandButton class="addButton"
id="checkStatusButton"
value ="Check Status"
action = "#{itemWeb.findItem}">
<f:ajax execute="checkStatusForm"
event="click"
render="statusLabel"/>
</h:commandButton>
<h:outputText id="statusLabel"
value="#{itemWeb.foundItem.status}">
</h:outputText>
The page refresh because you do not use JSF Standard tags(h:head, h:body).
Thus, you should change the index.xhtml to below example.
<!--
Index.html setup
Holds the form for input data
-->
<!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">
<h:head>
<link href='http://fonts.googleapis.com/css?family=Roboto'
rel='stylesheet' type='text/css'></link>
<link href='resources/css/main.css'
rel='stylesheet' type='text/css'></link>
<title>
<ui:insert name="title"
Library Management System
</ui:insert>
</title>
<!--
Quick style setup..
-->
</h:head>
<h:body>
<h:form id="checkStatusForm">
<div class="group">
<h:inputText id="searchCheckInput"
value="#{itemWeb.searchString}">
</h:inputText>
<label>Search By Title..</label>
<span class="highlight"></span>
<span class="bar"></span>
</div>
<h:commandButton class="addButton"
id="checkStatusButton"
value ="Check Status"
action ="#{itemWeb.findItem}">
<f:ajax execute="checkStatusForm"
event="action"
render="statusLabel"/>
</h:commandButton>
<h:outputText id="statusLabel"
value ="#{itemWeb.foundItem.status}">
</h:outputText>
</h:form>
</h:body>
</html>
See also: Adding HTML Head and Body Tags
Try to process only the desired field rather than the whole form, in the execute attribute:
<h:commandButton class="addButton" id="checkStatusButton" value ="Check Status" action = "#{itemWeb.findItem}">
<f:ajax execute="searchCheckInput" event="click" render="statusLabel"/>
</h:commandButton>
You need to use event="action" instead of event="click". The event="action" is namely the default event the is listening on when nested in an h:commandButton component.
An example is shown below.
xhtml
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<f:view contentType="text/html">
<h:head>
<f:facet name="first">
<meta content='text/html; charset=UTF-8' http-equiv="Content-Type"/>
<title>ajax-call</title>
</f:facet>
</h:head>
<h:body>
<h:form id="checkStatusForm">
<h:inputText id="searchCheckInput"
value="#{itemWeb.searchString}">
</h:inputText>
<label>Search By Title..</label>
<br/>
<h:commandButton class="addButton"
id="checkStatusButtonListener"
value ="Check Status (Listener)"
actionListener="#{itemWeb.findItemListener}">
<f:ajax execute="checkStatusForm"
event="action"
render="statusLabel"/>
</h:commandButton>
<h:commandButton class="addButton"
id="checkStatusButton"
value ="Check Status"
action="#{itemWeb.findItem}">
<f:ajax execute="checkStatusForm"
event="action"
render="statusLabel"/>
</h:commandButton>
<br/>
<h:outputText id="statusLabel"
value ="#{itemWeb.foundItem.status}">
</h:outputText>
</h:form>
</h:body>
</f:view>
</html>
managedbean
package com.wittakarn.view;
import com.wittakarn.model.Item;
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.event.ActionEvent;
/**
*
* #author Wittakarn
*/
#ViewScoped
#ManagedBean(name = "itemWeb")
public class ItemWeb implements Serializable{
private String searchString;
private Item foundItem;
public ItemWeb(){
foundItem = new Item();
}
public String getSearchString() {
return searchString;
}
public void setSearchString(String searchString) {
this.searchString = searchString;
}
public Item getFoundItem() {
return foundItem;
}
public void setFoundItem(Item foundItem) {
this.foundItem = foundItem;
}
public void findItem(){
foundItem.setStatus("status A");
}
public void findItemListener(ActionEvent event){
foundItem.setStatus("status B");
}
}
domain
package com.wittakarn.model;
import java.io.Serializable;
/**
*
* #author Wittakarn
*/
public class Item implements Serializable{
private String status;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}

JSF 2.0 AJAX: jsf.ajax.request to call method not only rerender an area of page

I'm looking for a soultion of the following problem:
_The is a list of links with different types of cars.
_The user can click on each car in the list and a ajax request should be sent.
_The response of the ajax request should be dependent on the id (of each car) and displayed in an panelGroup.
So what I need is a possibility to call a method on the backing-bean. Additionally, this method should be called with a car id as its parameter.
My code so far looks like:
...
function showDetails(detailsFor){
jsf.ajax.request(this, event, {render: 'form1:carDetails'});
}
...
<ul>
<ui:repeat value="#{carTree.getCars)}" var="car">
<h:outputScript name="jsf.js" library="javax.faces" target="head" />
<li onclick="showDetails(#{car.id});">#{car.name}</li>
</ui:repeat>
</ul>
...
<h:panelGroup id="carDetails" layout="block" style="float:left;">
// need the details of each 'selected /clicked' car here
</h:panelGroup>
...
And the method in the backing bean should look like:
public class CarTree {
...
public String getCarDetails(int carid){
return "The car details for the car id "+carid+" are......";
}
...
}
I've no idea how to call a method by using the new JSF 2.0 AJAX functionality. Please, help me...
Use f:setPropertyActionListener to pass a object from JSF page to your backend. This tag is especially useful when you are using repeatable components like datatable
No need to use raw JavaScript, you can use <f:ajax />. Plus instead of worrying about Car id and all, just send it completely to backing bean.
Here is a sample example:
The Car class:
public class Car {
int id;
String brand;
String color;
public Car(int id, String brand, String color) {
this.id = id;
this.brand = brand;
this.color = color;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
}
The CarTree class:
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
#ManagedBean(name = "CarTree")
#RequestScoped
public class CarTree {
List<Car> carList;
Car selectedCar;
public Car getSelectedCar() {
return selectedCar;
}
public void setSelectedCar(Car selectedCar) {
this.selectedCar = selectedCar;
}
public List<Car> getCars() {
return carList;
}
public void setCars(List<Car> carList) {
this.carList = carList;
}
public CarTree() {
carList = new ArrayList<Car>();
carList.add(new Car(1, "jaguar", "grey"));
carList.add(new Car(2, "ferari", "red"));
carList.add(new Car(3, "camri", "steel"));
}
}
The JSF 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">
<h:head>
<title>Facelet Title</title>
</h:head>
<h:body id="mainBody">
<h:form id="carForm">
<h:dataTable value="#{CarTree.cars}" var="car">
<h:column>
<h:outputText value="#{car.id}"/>
</h:column>
<h:column>
<h:outputText value="#{car.brand}"/>
</h:column>
<h:column>
<h:outputText value="#{car.color}"/>
</h:column>
<h:column>
<h:commandButton value="Show Car Detail" >
<f:setPropertyActionListener target="#{CarTree.selectedCar}" value="#{car}"/>
<f:ajax render=":carForm:carDetails" />
</h:commandButton>
</h:column>
</h:dataTable>
<h:panelGroup id="carDetails" layout="block" style="float:left;">
<h:outputText value="#{CarTree.selectedCar.id}" />
<h:outputText value="#{CarTree.selectedCar.brand}" />
<h:outputText value="#{CarTree.selectedCar.color}" />
</h:panelGroup>
</h:form>
</h:body>
</html>
Hope this helps.
I haven't tested myself, but I'd suggest you try something like this (assuming your class CarTree is #Named and, therefore, can be referred to inside the JSF page using the name carTree):
<ul>
<ui:repeat value="#{carTree.getCars)}" var="car">
<li><h:commandLink action="#{carTree.getCarDetails(car.id)}" value="#{car.name}">
<f:ajax render="carDetails" />
</h:commandLink></li>
</ui:repeat>
</ul>
...
<h:panelGroup id="carDetails" layout="block" style="float:left;">
// need the details of each 'selected /clicked' car here
</h:panelGroup>
I think the contents of the action property in the <h:commandLink /> can also be coded as the listener property in the <f:ajax /> tag. Don't know if there's any difference...
If you don't want to use <h:commandLink /> you could replace it with <h:outputText /> and add the property event="click" to the <f:ajax /> tag. I think that would work as well. In this case, the method call would have to be in the listener property of the <f:ajax /> tag.

Resources