domingo, 9 de marzo de 2014

ManagedBean

Páginas del tipo XHTML son las responsables de recibir las informaciones del usuario y enviarlas a nuestro bean (ManagedBean), no se colocan reglas de negocio, solo reglas básicas de visualización.

Nuestro bean es el responsable de decidir que pasará cuando estas informaciones sean recibidas, es decir, las acciones a ser realizadas. Sirve como un canal entre la interfaz gráfica (página web) y la parte interna de nuestra aplicación (back-end).

ManagedBean no debe realizar operaciones en la base de datos (Insert, update, remove) directamente, solo tiene que recibir la requisición y llamar a la clase correspondiente.

Teoría

Práctica

  • Creamos una clase modelo Persona:
 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
package Model;

public class Persona {
 //Variables
 private String nombre;
 private String edad;

 //Getters & Setters
 public String getNombre() {return nombre;}
 public void setNombre(String nombre) {this.nombre = nombre;}
 public String getEdad() {return edad;}
 public void setEdad(String edad) {this.edad = edad;}
 
 //Full constructor
 public Persona(String nombre, String edad) {
  super();
  this.nombre = nombre;
  this.edad = edad;
 }

 //Empty constructor
 public Persona() {
  super();
  this.nombre = "";
  this.edad = "";
 } 
}

  • Creamos nuestro bean PersonaBean:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
package Controller;

import javax.faces.bean.ManagedBean;

import Model.Persona;

@ManagedBean
public class PersonaBean {
 //Instances
 private Persona objPersona;
 
 //Constructor
 public PersonaBean(){
  this.objPersona = new Persona();
 }

 //Getters & Setters
 public Persona getObjPersona() {return objPersona;}
 public void setObjPersona(Persona objPersona) {this.objPersona = objPersona;}
 
}

  • Creamos la página xhtml persona.xhtml:

 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="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">
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
 <title>Insert title here</title>
</head>
<h:body>
 <h:form id="frm">
  <h:outputLabel value="Nombre: " for="nombre" />
  <h:inputText value="#{personaBean.objPersona.nombre}" id="nombre" /><br />
  
  <h:outputLabel value="Edad: " for="edad" />
  <h:inputText value="#{personaBean.objPersona.edad}" id="edad" /><br />
  
  <h:commandButton value="Registrar" /><hr/>
  
  <h:outputLabel value="Nombre digitado:  #{personaBean.objPersona.nombre} " /><br />
  <h:outputLabel value="Edad digitada: #{personaBean.objPersona.edad} " />
 </h:form>
</h:body>
</html>

Repositório GitHub

Tutorial paso a paso


No hay comentarios:

Publicar un comentario