Professional Documents
Culture Documents
Prctica 1
Prctica nmero 1:
Descripcin: Creacin de un JavaBean
Objetivos:
Primera toma de contacto con Netbeans como IDE
Primera toma de contacto con Sun Application Server 9 como Servidor
de Aplicaciones
Conocer las caractersticas principales de un JavaBean, para entender
Prctica 1
Arrancamos Netbeans.
Creamos un nuevo proyecto: ejb01-javabean:
Prctica 1
Prctica 1
Prctica 1
Modificamos el archivo:index.jsp
<jsp:useBean id="libro" class="cursoEjb.LibroListenerBean" scope="session" />
<%=session.getAttribute("libro") + "<br>" %>
<html>
<head>
<title>JavaBeans - Curso EJB</title>
</head>
<body>
<b>Guardamos los datos...</b><p>
<jsp:setProperty name="libro" property="titulo" value="Avanced JavaServer Pages" />
<jsp:setProperty name="libro" property="autor" value="David M. Geary" />
<b>Recuperamos los datos...</b><br>
<jsp:getProperty name="libro" property="titulo" /><br>
<jsp:getProperty name="libro" property="autor" /><br>
</body>
</html>
Prctica 1
Prctica 1
Advanced Menu
Eliminamos Mozilla y firefox, y nos quedamos slo con el browser de
swing.
Prctica 1
Prctica 1
Configuracin de konqueror:
Prctica 1
Prctica 1
Prctica 2
Prctica nmero 2:
Descripcin: Creacin de un Stateless EJB
Primera toma de contacto con los EJBs dentro del entorno Netbeans
Primera toma de contacto con las anotaciones, y cmo pueden facilitarnos la
vida.
Construccin de un EJB simple, que realice las funciones de una calculadora.
Ser una aplicacin que tenga un Servlet que haga la llamada al EJB
REIVINDIQUEMOS LO SIMPLE:
No hay Xdoclet.
El packaging es automtico.
No hay que crear descriptores (el entorno o el contenedor -segn el caso- lo hacen
de manera automtica)
No hay que crear interfaces HOME como hacamos en eclipse a travs de la
herramienta Xdoclet y la opcin PackageSubstitution cuando creamos EJBs.
Crear EJB con anotaciones es fcil y rpido.
No tenemos la obligacin de que los nombres de los Servlets terminen en Servlet, ni
que los nombres de los Beans terminen en Bean.
No hay que crear los mtodos ejbActivate y ejbPassivate; el contenedor realiza el
trabajo sucio.
Prctica 2
Prctica 2
Prctica 2
Prctica 2
Prctica 2
Prctica 2
Prctica 2
import javax.ejb.Stateless;
@Stateless
public class CalculadoraBean implements ejb02.CalculadoraRemote {
/** Creates a new instance of CalculadoraBean */
public CalculadoraBean() {
}
public int suma(int
a, int b) {
suma
return a+b;
}
public int resta(int
a, int b) {
resta
return a-b;
}
public int divide(int
a, int b) {
divide
if (b == 0) {
throw new IllegalArgumentException("No puedo dividir por 0");
}
return a / b;
}
public int multiplica(int
a, int b) {
multiplica
return a*b;
}
}
Prctica 2
Prctica 2
Prctica 2
Prctica 2
Prctica 2
Prctica 2
Prctica 2
Prctica 3
Prctica nmero 3:
Descripcin: Creacin de un Stateful EJB
Primera toma de contacto con los EJBs de tipo statefull
llamada al EJB
Prctica 3
Prctica 3
Prctica 3
Una vez de
pulsemos Finish,
desplegamos el
rbol de proyectos y
pulsamos click
derecho sobre
ejb03-carro-ejb tal
como en la figura:
Prctica 3
Prctica 3
Prctica 3
Prctica 3
Prctica 3
En el asistente,
proporcionamos estos
datos:
Y este cdigo:
package util;
Prctica 3
Y este cdigo:
package util;
/**
*
* @author jcarlos
*/
public class IdVerificador {
public IdVerificador() {
}
public boolean validar(String id) {
boolean result = true;
for (int i = 0; i < id.length(); i++) {
if (Character.isDigit(id.charAt(i))
==
false) {
result = false;
}
}
return result;
}
}
Prctica 3
El cdigo del
Bean es el
siguiente
(1/2):
@Stateful
public class CarroBean implements ejb03.Carro {
/** Creates a new instance of CarroBean */
List<String> contenidos;
String IdCliente;
String nombreCliente;
public CarroBean()
{
CarroBean
}
persona) throws LibroException {
public void inicializar(String
inicializar
if (persona == null) {
throw new LibroException("No se permite persona con
valor Null");
} else {
nombreCliente = persona;
}
IdCliente = "0";
contenidos = new ArrayList<String>();
}
// --->
---> Continua en la siguiente pagina
Prctica 3
Prctica 3
Prctica 3
Prctica 3
Prctica 3
Prctica 3
Prctica 4
Prctica nmero 4:
Descripcin: Creacin de un Message Driven Bean y conocer
usando el sistema pb-project (Java Blue Prints Project).
Objetivos:
Primera toma de contacto con los MDB
Primera toma de contacto con el sistema pb-project
Conocer las caractersticas principales de un MDB, para entender
Prctica 4
Prctica 4
Por:
<property name="bp-project.home" value=poner el path <bp-project.home>"/>
<import file="${bp-project.home}/main.xml" />
Prctica 4
Por:
<property name="is.war.module" value="true"/>
<property name="bp-project.home" value="path de <bp-project.home>"/>
<import file="${bp-project.home}/main.xml" />
Prctica 4
Prctica 4
Proyecto Web
<?xml version="1.0"?>
<project name="bp-web-project" default="default" basedir=".">
<property name="is.war.module
is.war.module"
is.war.module value="true"/>
<import file="bp-project/main.xml"/>
</project>
Prctica 4
Proyecto Java Persistente Unit.
<?xml version="1.0" encoding="UTF-8"?>
<project name="hello-pu" default="default" basedir=".">
<description>Builds, tests, and runs the project hello-pu.</description>
<property name="is.jar.module
is.jar.module"
is.jar.module value="true"/>
<property name="is.persistence
is.persistenceis.persistence-unit.module"
unit.module value="true"/>
<import file="bp-project/main.xml"/>
</project>
Prctica 4
Prctica 4
Prctica 4
Prctica 4
Prctica 4
Prctica 4
Prctica 4
C:\CursoEJB\proyectos\ejb04-mensajesimple
O en otro caso:
/root/ejb04
root/ejb04/ejb04-mensajesimple
Prctica 4
Por:
<property name="is.ear.module" value="true"/>
<import file=./bp-project/main.xml" />
Prctica 4
Prctica 4
Prctica 4
msg.getText());
} else {
logger.warning("Mensaje de tipo
erroneo: +
mensajeEntrante.getClass().getName());
}
} catch (JMSException e) {
e.printStackTrace();
mdc.setRollbackOnly();
} catch (Throwable te) {
te.printStackTrace();
}
}
}
Prctica 4
El cdigo del cliente, debe ser el siguiente:
public class ClienteMensajeSimple {
System.out.println("Para ver si el bean recibio+
+mensajes,");
@Resource(mappedName = "jms/ConnectionFactory")
System.out.println( mirar en el fichero: +
private static ConnectionFactory connectionFactory;
@Resource(mappedName = "jms/MensajeSimpleBean")
<install>/domains/domain1/logs/server.log.");
private static Queue queue;
} catch (JMSException e) {
public static void main(String[] args) {
System.out.println("Se elevo una excepcion: +
Connection connection = null;
e.toString());
Session session = null;
} finally {
MessageProducer messageProducer = null;
if (connection != null) {
TextMessage message = null;
try {
final int NUM_MSGS = 3;
connection.close();
try {
} catch (JMSException e) {
connection = connectionFactory.createConnection();
}
session = connection.createSession(false,
} // if
Session.AUTO_ACKNOWLEDGE);
messageProducer = session.createProducer(queue);
System.exit(0);
message = session.createTextMessage();
} // finally
} // main
for (int i = 0; i < NUM_MSGS; i++) {
message.setText("Este es el mensaje numero: " +public void onMessage(Message message) {
(i + 1));
}
System.out.println("Enviando mensaje: " +
}
// class
message.getText());
messageProducer.send(message);
}
Prctica 4
Prctica 4
Una vez ms, editaremos nuestro fichero build.xml, para aadir lo siguiente:
<target name="create
createcreate-queue"
queue description="create JMS queue">
<antcall target="create-jms-resource">
<param name="jms.restype" value="javax.jms.Queue" />
<param name="jms.resource.property" value="Name=PhysicalQueue" />
<param name="jms.resource.name" value="jms
jms/
jms/MensajeSimpleBean"
MensajeSimpleBean />
</antcall>
</target>
<target name="create
createcreate-cf"
cf description="create JMS connection factory">
<antcall target="create-jms-connection-factory">
<param name="jms.restype" value="javax.jms.ConnectionFactory
javax.jms.ConnectionFactory"
javax.jms.ConnectionFactory />
<param name="jms.resource.name" value="jms/ConnectionFactory" />
</antcall>
</target>
<target name="delete
deletedelete-queue"
queue
description="delete JMS queue">
<antcall target="delete-jms-resource">
<param name="jms.resource.name" value="jms/MensajeSimpleBean" />
</antcall>
</target>
deletecf"
<target name="delete
delete
-cf
description="delete JMS connection factory">
<antcall target="delete-jms-resource">
<param name="jms.resource.name" value="jms/ConnectionFactory" />
</antcall>
</target>
Prctica 4
$sudo su
#export PATH=/opt/SUNWapp/lib/ant/bin:/opt/jdk/bin:$PATH
#export JAVA_HOME=/opt/jdk
#ant create-cf
#ant create-queue
Debemos obtener
lo siguiente:
Prctica 4
Prctica 4
Prctica 5
Prctica nmero 5:
Descripcin: Creacin de un bean de entidad, y primer
acercamiento a la base de datos derby para la funcin de
almacn de datos.
Objetivos:
Primera toma de contacto con los entity beans.
Primera toma de contacto con derby
Conocer las caractersticas principales de un entity bean.
Prctica 5
Prctica 5
Prctica 5
Prctica 5
Prctica 5
Prctica 5
Prctica 5
Prctica 5
Prctica 5
@Entity
Prctica 5
Prctica 5
Prctica 5
super.init(config);
}
}
Prctica 5
Prctica 5
try {
// Comenzamos una transaccion porque usamos un Entity Manager JTA.
utx.begin();
} catch (Exception e) {
throw new ServletException(e);
}
EntityManager em = emf.createEntityManager();
try {
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.println("<HTML> <HEAD> <TITLE>Registro de nuevo usuario " +
"</TITLE> </HEAD> <BODY BGCOLOR=white>");
Prctica 5
String nombre = req.getParameter("nombre");
String password = req.getParameter("password");
CredencialUsuario credencial = new CredencialUsuario(nombre, password);
// em.persist hace que el objeto se vuelva persistente.
em.persist(credencial);
out.println("Se ha creado correctamente el nuevo usuario. " +
"Haz click <A HREF=\"login.html\"> aqui </A> para logarte.");
out.println("</BODY> </HTML> ");
utx.commit();
} catch (Exception e) {
try {
utx.rollback();
} catch (Exception ee) {
// Excepcion
}
throw new ServletException(e);
} finally {
em.close();
}
}
public void
super.init(config);
}
}
Prctica 5
Prctica 5
Prctica 5
Prctica 5
Prctica 5
Prctica 5
Prctica 5
Prctica 5
Prctica 5
Prctica 5
Si recordamos el
cdigo fuente de
la clase:
Prctica 5
Prctica 5
Prctica 5
Prctica 5
Prctica 5
Prctica 5
Prctica 5
Prctica 5
Prctica 5
Prctica 5
Prctica 5