14 septiembre, 2020

Crear un Formulario de componentes en Eclipse con JSF 2.3 y Primefaces 7.0

Herramientas

Eclipse IDE

WildFly 20.0

Pasos

1. Crear un Dynamic Web Project




Marcamos la casilla para generar el archivo descriptor web.xml


Agregamos  el URL Pattern *.xhtml



2. Configurar las facetas del proyecto

Clic derecho al proyecto / Build Path / Configure Build Path / Project Facets

Debemos marcar las siguientes casillas

Tambien debemos tener configurado el servidor para tomar las librerías de JSF 2.3




3. Configurar el archivo descriptor web.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="4.0"
  <display-name>Componentes_JSF2.3</display-name>
 
  <welcome-file-list>
      <welcome-file>index.xhtml</welcome-file>
  </welcome-file-list>
 
  <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>/faces/*</url-pattern>
      <url-pattern>*.xhtml</url-pattern>
  </servlet-mapping>
 
</web-app>


Ejemplo 1

Crear la clase PersonaBean.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package ejemplo1;
 
import java.util.ArrayList;
import java.util.List;
 
import javax.enterprise.context.RequestScoped;
import javax.inject.Named;
 
@Named
@RequestScoped
public class PersonaBean {
 
  private String nombre; // Campo
  private int edad; // Campo
  private String descripcion; // Área de texto
  private String dia; // Campo de selección
  private String genero; // RadioButton
  private String[] idioma; // CheckBox
  private List<String> profesionList; // Lista de seleccion multiple
  private List<String> profesionSeleccionada; // Lista para almacenar los elementos seleccionados
 
  public PersonaBean() {
      profesionList = new ArrayList<String>();
      profesionList.add("Bachiller");
      profesionList.add("Técnico");
      profesionList.add("Tecnólogo");
      profesionList.add("Profesional");
      profesionList.add("Especialista");
      profesionList.add("Maestra");
      profesionList.add("Doctorado");
  }
 
  public String getNombre() {
      return nombre;
  }
 
  public void setNombre(String nombre) {
      this.nombre = nombre;
  }
 
  public int getEdad() {
      return edad;
  }
 
  public void setEdad(int edad) {
      this.edad = edad;
  }
 
  public String getDescripcion() {
      return descripcion;
  }
 
  public void setDescripcion(String descripcion) {
      this.descripcion = descripcion;
  }
 
  public String getDia() {
      return dia;
  }
 
  public void setDia(String dia) {
      this.dia = dia;
  }
 
  public String getGenero() {
      return genero;
  }
 
  public void setGenero(String genero) {
      this.genero = genero;
  }
 
  public String[] getIdioma() {
      return idioma;
  }
 
  public void setIdioma(String[] idioma) {
      this.idioma = idioma;
  }
 
  public List<String> getProfesionList() {
      return profesionList;
  }
 
  public void setProfesionList(List<String> profesionList) {
      this.profesionList = profesionList;
  }
 
  public List<String> getProfesionSeleccionada() {
      return profesionSeleccionada;
  }
 
  public void setProfesionSeleccionada(List<String> profesionSeleccionada) {
      this.profesionSeleccionada = profesionSeleccionada;
  }
 
}

Crear las siguientes páginas



index.xhtml


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
<?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">
<h:head>
  <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
  <title>Página Registro</title>
</h:head>
<h:body>
  <h2>Formulario de Registro</h2>
  <hr/>
  <h:form>
      <h:panelGrid columns="2" border="2">
          <h:outputLabel value="Nombre" for="nombre" />
          <h:inputText value="#{personaBean.nombre}" id="nombre" style="width: 350px" />
 
          <h:outputLabel value="Edad" for="edad" />
          <h:inputText value="#{personaBean.edad}" id="edad" style="width: 350px"/>
 
          <h:outputLabel value="Descripción" for="descripcion" />
          <h:inputTextarea value="#{personaBean.descripcion}" cols="10" rows="5" id="descripcion" style="width: 350px"/>
 
          <h:outputLabel value="Día" for="dia" />
          <h:selectOneMenu value="#{personaBean.dia}" id="dia" style="width: 350px">
              <f:selectItem itemValue="Lunes" itemLabel="Lunes" />
              <f:selectItem itemValue="Martes" itemLabel="Martes" />
              <f:selectItem itemValue="Miercoles" itemLabel="Miércoles" />
              <f:selectItem itemValue="Jueves" itemLabel="Jueves" />
              <f:selectItem itemValue="Viernes" itemLabel="Viernes" />
              <f:selectItem itemValue="Sabado" itemLabel="Sábado" />
              <f:selectItem itemValue="Domingo" itemLabel="Domingo" />
          </h:selectOneMenu>
 
          <h:outputLabel value="Género" for="genero" />
          <h:selectOneRadio value="#{personaBean.genero}" id="genero">
              <f:selectItem itemValue="Masculino" itemLabel="Masculino" />
              <f:selectItem itemValue="Femenino" itemLabel="Femenino" />
          </h:selectOneRadio>
 
          <h:outputLabel value="Idioma" for="idioma" />
          <h:selectManyCheckbox value="#{personaBean.idioma}" id="idioma" layout="pageDirection">
              <f:selectItem itemValue="Español" itemLabel="Español" />
              <f:selectItem itemValue="Ingles" itemLabel="Ingles" />
              <f:selectItem itemValue="Frances" itemLabel="Frances" />
              <f:selectItem itemValue="Aleman" itemLabel="Aleman" />
          </h:selectManyCheckbox>
 
          <h:outputLabel value="Profesión" for="profesion" />
          <h:selectManyListbox value="#{personaBean.profesionSeleccionada}">
              <f:selectItems value="#{personaBean.profesionList}" />
          </h:selectManyListbox>
      </h:panelGrid>
 
      <br/><br/>
 
      <h:commandButton value="Enviar" action="datos"/>
  </h:form>
</h:body>
</html>

datos.xhtml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
<?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">
<h:head>
  <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
  <title>Página Confirmación</title>
</h:head>
<h:body>
  <h2>Bienvenido #{personaBean.nombre}</h2>
  <h:form>
      <h:panelGrid columns="2" border="2">
          <h:outputLabel value="Nombre" for="nombre" />
          <h:outputText value="#{personaBean.nombre}" id="nombre" style="width: 350px"/>
 
          <h:outputLabel value="Edad" for="edad" />
          <h:outputText value="#{personaBean.edad}" id="edad" style="width: 350px"/>
 
          <h:outputLabel value="Descripción" for="descripcion" />
          <h:inputTextarea value="#{personaBean.descripcion}" cols="10" rows="5" id="descripcion" style="width: 350px"/>
 
          <h:outputLabel value="Día Actual" for="dia" />
          <h:outputText value="#{personaBean.dia}" />
 
          <h:outputLabel value="Género" for="genero" />
          <h:outputText value="#{personaBean.genero}" />
 
          <h:outputLabel value="Idioma" for="idioma" />
          <h:panelGroup>
              <ul>
                  <ui:repeat var="idioma" value="#{personaBean.idioma}">
                      <li>#{idioma}</li>
                  </ui:repeat>
              </ul>
          </h:panelGroup>
 
          <h:outputLabel value="Profesión" for="profesion" />
          <h:panelGroup>
              <ul>
                  <ui:repeat var="profesion"
                      value="#{personaBean.profesionSeleccionada}">
                      <li>#{profesion}</li>
                  </ui:repeat>
              </ul>
          </h:panelGroup>
      </h:panelGrid>
 
      <br />
      <br />
 
      <h:commandButton value="Enviar" action="index" />
  </h:form>
</h:body>
</html>

Probar la aplicación


Ejemplo 2

Copiar el jar de primefaces en la carpeta lib del WebContent

Crear las siguietnes clases

Car.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package ejemplo2;
 
public class Car {
 
    private String id;
    private String brand;
    private int year;
    private String color;
    private int price;
    private boolean soldState;
 
    public String getId() {
        return id;
    }
 
    public void setId(String id) {
        this.id = id;
    }
 
    public String getBrand() {
        return brand;
    }
 
    public void setBrand(String brand) {
        this.brand = brand;
    }
 
    public int getYear() {
        return year;
    }
 
    public void setYear(int year) {
        this.year = year;
    }
 
    public String getColor() {
        return color;
    }
 
    public void setColor(String color) {
        this.color = color;
    }
 
    public int getPrice() {
        return price;
    }
 
    public void setPrice(int price) {
        this.price = price;
    }
 
    public boolean isSoldState() {
        return soldState;
    }
 
    public void setSoldState(boolean soldState) {
        this.soldState = soldState;
    }
 
    public Car(String id, String brand, int year, String color, int price, boolean soldState) {
        this.id = id;
        this.brand = brand;
        this.year = year;
        this.color = color;
        this.price = price;
        this.soldState = soldState;
    }
 
}

CarService.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package ejemplo2;
 
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
 
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Named;
 
@Named
@ApplicationScoped
public class CarService {
 
    private final static String[] colors;
 
    private final static String[] brands;
 
    static {
        colors = new String[10];
        colors[0] = "Black";
        colors[1] = "White";
        colors[2] = "Green";
        colors[3] = "Red";
        colors[4] = "Blue";
        colors[5] = "Orange";
        colors[6] = "Silver";
        colors[7] = "Yellow";
        colors[8] = "Brown";
        colors[9] = "Maroon";
 
        brands = new String[10];
        brands[0] = "BMW";
        brands[1] = "Mercedes";
        brands[2] = "Volvo";
        brands[3] = "Audi";
        brands[4] = "Renault";
        brands[5] = "Fiat";
        brands[6] = "Volkswagen";
        brands[7] = "Honda";
        brands[8] = "Jaguar";
        brands[9] = "Ford";
    }
 
    public List<Car> createCars(int size) {
        List<Car> list = new ArrayList<Car>();
        for (int i = 0; i < size; i++) {
            list.add(new Car(getRandomId(), getRandomBrand(), getRandomYear(), getRandomColor(), getRandomPrice(),
                    getRandomSoldState()));
        }
 
        return list;
    }
 
    private String getRandomId() {
        return UUID.randomUUID().toString().substring(0, 8);
    }
 
    private int getRandomYear() {
        return (int) (Math.random() * 50 + 1960);
    }
 
    private String getRandomColor() {
        return colors[(int) (Math.random() * 10)];
    }
 
    private String getRandomBrand() {
        return brands[(int) (Math.random() * 10)];
    }
 
    private int getRandomPrice() {
        return (int) (Math.random() * 100000);
    }
 
    private boolean getRandomSoldState() {
        return (Math.random() > 0.5) ? true : false;
    }
 
    public List<String> getColors() {
        return Arrays.asList(colors);
    }
 
    public List<String> getBrands() {
        return Arrays.asList(brands);
    }
}

PaginatorView.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package ejemplo2;
 
import java.io.Serializable;
import java.util.List;
 
import javax.annotation.PostConstruct;
import javax.faces.view.ViewScoped;
import javax.inject.Inject;
import javax.inject.Named;
 
@Named("dtPaginatorView")
@ViewScoped
public class PaginatorView implements Serializable {
 
    /**
     *
     */
    private static final long serialVersionUID = 3754000314652776248L;
 
    private List<Car> cars;
 
    @Inject
    private CarService service;
 
    @PostConstruct
    public void init() {
        cars = service.createCars(50);
    }
 
    public List<Car> getCars() {
        return cars;
    }
 
    public void setService(CarService service) {
        this.service = service;
    }
}


Probar la aplicación


Descargar proyecto

No hay comentarios, ¡cuéntame algo!

Me gustaría saber tu opinión. ¡Saludos!