JSF Converter and Injection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.mkyong; | |
import java.util.ArrayList; | |
import java.util.List; | |
import javax.annotation.PostConstruct; | |
import javax.enterprise.context.RequestScoped; | |
import javax.inject.Named; | |
@Named | |
@RequestScoped | |
public class CarController { | |
private Car selectedCar; | |
private List<Car> cars; | |
@PostConstruct | |
public void init() { | |
cars = new ArrayList<Car>(); | |
cars.add(new Car(1l)); | |
cars.add(new Car(2l)); | |
cars.add(new Car(3l)); | |
cars.add(new Car(4l)); | |
} | |
public Car getSelectedCar() { | |
return selectedCar; | |
} | |
public void setSelectedCar(Car selectedCar) { | |
this.selectedCar = selectedCar; | |
} | |
public void action() { | |
System.out.println("Car: " + selectedCar); | |
} | |
public List<Car> getCars() { | |
return cars; | |
} | |
} | |
---- | |
package com.mkyong; | |
import javax.inject.Named; | |
@Named | |
public class CarService { | |
public Car findById(Long valueOf) { | |
System.out.println("find by Id"); | |
return new Car(valueOf); | |
} | |
} | |
--- | |
package com.mkyong; | |
import javax.faces.component.UIComponent; | |
import javax.faces.context.FacesContext; | |
import javax.faces.convert.Converter; | |
import javax.faces.convert.FacesConverter; | |
import javax.inject.Inject; | |
@FacesConverter(forClass = Car.class, value = CarConverter.CONVERTER_ID) | |
public class CarConverter implements Converter { | |
public static final String CONVERTER_ID = "car.converter.id"; | |
@Inject | |
private CarService carService; | |
@Override | |
public Object getAsObject(FacesContext context, UIComponent component, String value) { | |
System.out.println("get as object" + carService); | |
return carService.findById(Long.valueOf(value)); | |
} | |
@Override | |
public String getAsString(FacesContext context, UIComponent component, Object value) { | |
return String.valueOf(((Car) value).getId()); | |
} | |
} | |
--- | |
package com.mkyong; | |
public class Car { | |
private Long id; | |
public Car(long id) { | |
this.id = id; | |
} | |
public Long getId() { | |
return id; | |
} | |
public void setId(Long id) { | |
this.id = id; | |
} | |
@Override | |
public String toString() { | |
return "Car [id=" + id + "]"; | |
} | |
} | |
--- | |
<h:form> | |
<p:selectOneListbox value="#{carController.selectedCar}" | |
converter="car.converter.id"> | |
<f:selectItems value="#{carController.cars}" /> | |
</p:selectOneListbox> | |
<p:commandButton value="ACtion" action="#{carController.action}" /> | |
</h:form> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment