init method with annotation PostConstruct create error - spring

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 ?

Related

Modal edit dialog on Primefaces with JSF

I'm trying to create some CRUD JSF application with edit/new screen implemented as a modal dialog. The problem is that I can't find a way how to make new and edit operation done by this dialog performed with ajax. With delete all was very simple (just ajax="true" option).
Here is a code of button which is used to show the dialog
<h:form id="dataForm">
<div class="ui-g">
<div class="ui-g-12 ui-md-9">
<p:dataGrid var="product" value="#{products.productList}" columns="3" layout="grid"
rows="12" paginator="true" id="products"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
rowsPerPageTemplate="6,12,16">
<f:event type="preRenderView" listener="#{products.preloadProductList}" />
<f:facet name="header">
Products
</f:facet>
<p:panel header="#{product.name}" style="text-align:center">
<h:panelGrid columns="1" style="width:100%">
<h:outputText value="#{product.name}"/>
<h:outputText value="#{product.price}"/>
<%-- Here new/edit dialog window is opened --%>
<p:commandLink update=":dataForm:productDetail" oncomplete="PF('productDialog').show()">
Edit
<f:setPropertyActionListener value="#{product}" target="#{products.product}"/>
</p:commandLink>
<p:commandLink update=":dataForm" action="#{products.deleteAction(product)}" ajax="true">
Delete
</p:commandLink>
</h:panelGrid>
</p:panel>
</p:dataGrid>
<ui:include src="WEB-INF/dialogs/edit_product.xhtml"/>
</div>
</div>
</h:form>
Here is dialog window which is moved to separete file edit_product.xhtml
<ui:composition
xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:p="http://primefaces.org/ui">
<p:dialog header="Product Info" widgetVar="productDialog" modal="true" showEffect="fade"
hideEffect="fade"
resizable="false">
<p:outputPanel id="productDetail" style="text-align:center;">
<p:panelGrid columns="2" rendered="#{not empty products.product}"
columnClasses="label,value">
<h:outputText value="Id:"/>
<h:outputText value="#{products.id}"/>
<h:outputText value="Name"/>
<h:inputText value="#{products.name}"/>
<h:outputText value="Price"/>
<h:inputText value="#{products.price}"/>
</p:panelGrid>
<h:commandButton value="Save" action="#{products.saveProduct}"/>
</p:outputPanel>
</p:dialog>
</ui:composition>
Here is Managed bean which is used by the Product dataGrid and dialog window.
#ManagedBean(name = "products")
#SessionScoped
public class ProductsBean {
private static final Logger logger = LoggerFactory.getLogger(ProductsBean.class);
#Inject
private ProductRepository productRepository;
private Product product;
private Collection<Product> productList;
public void preloadProductList(ComponentSystemEvent event) throws AbortProcessingException {
productList = productRepository.getAll();
}
public String getId() {
return String.valueOf(product.getId());
}
public void setId(String id) {
product.setId(Long.valueOf(id));
}
public String getName() {
return product.getName();
}
public void setName(String name) {
product.setName(name);
}
public int getPrice() {
return product.getPrice();
}
public void setPrice(int price) {
product.setPrice(price);
}
public Product getProduct() {
return this.product;
}
public void setProduct(Product product) {
this.product = product;
}
public Collection<Product> getProductList() {
logger.info("Get product list");
return productList;
}
public void newProductAction() {
this.product = new Product();
}
public void deleteAction(Product product) {
logger.info("Delete product");
productRepository.remove(product);
}
public void saveProduct() {
productRepository.merge(product);
}
}
No matter if I add ajax option or not the whole window is reloaded after Save button is pressed. Could you show me the right direction for the implementation, please?
P.S. If you need more code to answer you can find it here:
Main page with Product table https://github.com/usharik/GeekBrainsJavaEE/blob/master/lesson5-jpa/src/main/webapp/index.xhtml
Edit/New dialog https://github.com/usharik/GeekBrainsJavaEE/blob/master/lesson5-jpa/src/main/webapp/WEB-INF/dialogs/edit_product.xhtml

losing request parameter in jsf for second ajax poll call

I'm facing a problem with poll request, the first call is ok and the second is loosing the request parameter. Below is the code:
<h:form id="form">
<p:poll interval="10" listener="${emsstatbean.getEmsStat_list(request.getParameter('para'))}" update="emstatTable" />
<p:dataTable id="emstatTable" var="emsstat" value="${emsstatbean.getEmsStat_list(request.getParameter('para'))}" emptyMessage="No statistic found with given criteria" styleClass="table table-striped table-bordered table-hover" >
<p:column headerText="Server Hostname" >
<h:outputText value="#{emsstat.id.timeStamp}" />
</p:column>
<p:column headerText="Os name" >
<h:outputText value="#{emsstat.upTime}" />
</p:column>
<p:column headerText="Os name" >
<h:outputText value="${emsstat.state}" />
</p:column>
</p:dataTable>
</h:form>
and this is the bean class:
#ManagedBean(name = "emsstatbean")
public class EmsStatBean implements Serializable
{
public List<TibcoEmsStat> getEmsStat_list(int p)
{
return service.listEmsStats(p);
}
#ManagedProperty("#{emsStatService}")
EmsStatService service;
#PostConstruct
public void init()
{
}
public void setService(EmsStatService service)
{
this.service = service;
}
}
This is the URL called: content/public/TibcoEmsStat.xhtml?para=254
So when I paste that on browsers I'm getting the data table with all rows, but when I wait 10 sec I don't see content and I get "No statistic" found with given criteria, because parameter is empty.
Can you please help me to understand where is the issue?
this is how i fixed after reviewing some suggested link
added to the bean:
#ViewScoped
and a variable to store the id
public int ems_inst;
public int getEms_inst() {
return ems_inst;
}
public void setEms_inst(int ems_inst) {
this.ems_inst = ems_inst;
}
on the xhtml i did:
<f:metadata>
<f:viewParam name="ems_inst" value="#{emsstatbean.ems_inst}" />
</f:metadata>
<h:form id="form">
<p:poll interval="10"
listener="${emsstatbean.getEmsStat_list(emsstatbean.ems_inst)}" update="emstatTable" />
<p:dataTable id="emstatTable" var="emsstat" value="${emsstatbean.getEmsStat_list(emsstatbean.ems_inst)}"
all now is working fine
thanks

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?

To get Validation Messages from the Controller

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'}" />

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