Sesión 2. Profesor: Simon Pickin Track 2. Lecturer: Simon ...€¦ · Sesión 2. Profesor: Simon...

28
Sesión 2. Profesor: Simon Pickin Track 2. Lecturer: Simon Pickin EJB3 (en ingles/ in English) Java FX / Java FX script (en inglés/in English) Ruby / Ruby on Rails Groovy / Groovy on Grails Jakarta Struts Ajax Plantilla para la votación Ballot paper EJB3 JavaFX Ruby Groovy Jakarta Struts Ajax EJB3 JavaFX Ruby Groovy Jakarta Struts Ajax Ejemplo de votación válida (debe haber 1A, 2B, 2C, 1D) Example of a valid vote (there must be 1A, 2Bs, 2Cs, 1D) voter (votante) A B B C C D

Transcript of Sesión 2. Profesor: Simon Pickin Track 2. Lecturer: Simon ...€¦ · Sesión 2. Profesor: Simon...

Page 1: Sesión 2. Profesor: Simon Pickin Track 2. Lecturer: Simon ...€¦ · Sesión 2. Profesor: Simon Pickin Track 2. Lecturer: ... JPA EntityManagerFactory ... If a user is fond of a

Sesión 2. Profesor: Simon Pickin Track 2. Lecturer: Simon Pickin

• EJB3 (en ingles/ in English) • Java FX / Java FX script (en inglés/in English) • Ruby / Ruby on Rails • Groovy / Groovy on Grails • Jakarta Struts • Ajax

Plantilla para la votación Ballot paper

EJB3 JavaFX Ruby Groovy Jakarta Struts Ajax

EJB3 JavaFX Ruby Groovy Jakarta Struts Ajax

Ejemplo de votación válida (debe haber 1A, 2B, 2C, 1D) Example of a valid vote (there must be 1A, 2Bs, 2Cs, 1D)

voter (votante)

A B B C C D

Page 2: Sesión 2. Profesor: Simon Pickin Track 2. Lecturer: Simon ...€¦ · Sesión 2. Profesor: Simon Pickin Track 2. Lecturer: ... JPA EntityManagerFactory ... If a user is fond of a

Communication

Software

2007-2008

EJB 3

Javier Cuadrado López

Dario Dosantos Moreno

Juan González Adrados

Departamento de Ingeniería Telemática Universidad Carlos III de Madrid

Communication

Software

2008-200922

Contents

1. Introduction

2. Overview

3. Development

4. Usage

5. Conclusions

6. References

7. Questions?

Communication

Software

2008-20093

1. Introduction

• General Concept– EJB (Enterprise Java Beans) is an architecture of

logical components server-side for the construction of enterprise applications (started in 1998 with EJB 1.0).

– Encapsulates the business logic of an application.– API from J2EE (Java Enterprise Edition).

– Provide a distributed component model.

– Let the programmer pay attention in business logic development itself.

– Flexible and reusable components (EJB Server, Enterprise Beans…)

3

Communication

Software

2008-20094

1. Introduction

• EJB 3– Included in last J2EE specification (Java EE 5).

– Java community now knows much more about problems involved in building web applications so we have a much powerful architecture than before.

– It appears, therefore, as a substitute for EJB 2.X in order to make things simpler.

– Used by a lot of companies to create big web applications in a simple and easy way.

4

Page 3: Sesión 2. Profesor: Simon Pickin Track 2. Lecturer: Simon ...€¦ · Sesión 2. Profesor: Simon Pickin Track 2. Lecturer: ... JPA EntityManagerFactory ... If a user is fond of a

Communication

Software

2008-20095

1. Introduction

• Main New Features– Using of metadata annotations to substitute the

deployment descriptor (XML file) e.g: @stateless.– EJB2 callbacks (as ejbPassivate()) are defined using

also annotations placed in a method called by the container.

– No home interface.– Business interface does not implement EJBObject or

EJBLocalObject interfaces.– Bean class does not implement an EnterpriseBean

type.– EJB3 entities are created using a new() constructor

and managed by an EntityManager.5

Communication

Software

2008-2009

2. Overview

6

Communication

Software

2008-2009

2. Overview

7

• Main characteristics

• Simplify EJB2.X

• POJO-like beans

• Persistence API

Communication

Software

2008-2009

2. Overview

8

• Strong points

• Useful for different applications

• Robust, secure, all Java advantages

• Simpler than previous versions

• Quite used worldwide

Page 4: Sesión 2. Profesor: Simon Pickin Track 2. Lecturer: Simon ...€¦ · Sesión 2. Profesor: Simon Pickin Track 2. Lecturer: ... JPA EntityManagerFactory ... If a user is fond of a

Communication

Software

2008-2009

2. Overview

9

• Limitations

• Still can’t be called “easy”

• Has to be learnt apart from standard Java

• Very heavy if application is not really big

Communication

Software

2008-2009

2. Overview

10

Communication

Software

2008-200911

3. Development

• No home interface

• Business interface does not extend EJBObject or EJBLocalObject � it is a POJI

• Bean class does not implement an EnterpriseBean � it is a POJO

• No needed callback methods (ejbCreate, ejbActivate, ejbLoad...)

• No needed deployment descriptor

11

Communication

Software

2008-200912

3. Development

Tags preceded by “@”

Example (Entity Beans):

@Entity

@Table(name=“EMPLOYEE”)

@SecondaryTables({@SecondaryTable(name=“DEPARTMENT”join={@JoinColumn(name=“DEPT_ID”)})

Public class Owner {

@Id (generate=GeneratorType.AUTO)

@Column(name=“EMPLOYEE”) private long id;

@Column(name=“NAME”) private String name;

@Column(name=“DEPT”) @ManyToOne private String department;

.....

12

Page 5: Sesión 2. Profesor: Simon Pickin Track 2. Lecturer: Simon ...€¦ · Sesión 2. Profesor: Simon Pickin Track 2. Lecturer: ... JPA EntityManagerFactory ... If a user is fond of a

Communication

Software

2008-200913

3. Development

Persistence: JPA

EntityManagerFactory emf = Persistance.createEntityManagerFactory(“myapp”);

EntityManager.em = emf.createEntityManager();

Employee myEmp = new Employee();

em.persist(myEmp);

em.find(Employee.class, id);

em.remove(myEmp);

Configuration that describes the persistence unit: persistance.XML file

<persistence>

<persistence-unit name="myapp">

… 13

Communication

Software

2008-200914

3. Development

Using Queries:

• Query Language: JPQL

EntityManager.createQuery(String QUERY);

Not SQL, but similar:

SELECT NEW example.EmployeeDetails(e.id, e.name, e.department) FROM Employee e;

• Also possible to use SQL

EntityManager.createNativeQuery(String SQL_QUERY);

14

Communication

Software

2008-200915

4. Usage

• Web application framework: JBoss Seam

• Enterprise Content Management: Nuxeo

• Service-oriented architecture: GraniteDS

• Application framework: Spring Framework

• Software application: Cameleon Commerce Suite

Communication

Software

2008-200916

5. Conclusions

• Pros– EJB 3 is a good substitute for the previous version.– New and better features.– Better performance than EJB 2.1– Simplicity gained with the use of annotations which “make

the path easier” for developers.

• Cons– Still more features of the EJB architecture to simplify.– For this, it has started the development of the next version

of EJBs (EJB 3.1).• .war packaging of EJB components• Application initialization and shutdown events• EJB Lite: definition of a subset of EJB• …

Page 6: Sesión 2. Profesor: Simon Pickin Track 2. Lecturer: Simon ...€¦ · Sesión 2. Profesor: Simon Pickin Track 2. Lecturer: ... JPA EntityManagerFactory ... If a user is fond of a

Communication

Software

2008-200917

6. References

• EasyBeans User Guidehttp://www.easybeans.org/doc/userguide/en/chunk-integrated/index.html

• Enterprise Java Beans on Wikipediahttp://en.wikipedia.org/wiki/Enterprise_JavaBean

• Simplifying EJB Development with EJB 3.0

http://www.oracle.com/technology/tech/java/newsletter/articles/simplifying_ejb3.html

• JBoss EJB 3.0 Tutorial

http://docs.jboss.org/ejb3/app-server/tutorial/• Enterprise JavaBeans Technology

http://java.sun.com/products/ejb/

Communication

Software

2008-200918

7. Questions?

Page 7: Sesión 2. Profesor: Simon Pickin Track 2. Lecturer: Simon ...€¦ · Sesión 2. Profesor: Simon Pickin Track 2. Lecturer: ... JPA EntityManagerFactory ... If a user is fond of a

1

JavaFX, released on December 4th 2008, is a scripting Language that allows

developers:

To create Rich Internet Applications (think about Google Docs, Youtube or

Windows Live).

To deploy these application on many platforms at once, without having to

make huge modifications to the core structure or code using the JRE.

To access much of the source code to improve it or go around it.

Integration with common development tools, which the 6 million Java

developer base are used to.

Additional tools to test the software and port graphics.

2

Page 8: Sesión 2. Profesor: Simon Pickin Track 2. Lecturer: Simon ...€¦ · Sesión 2. Profesor: Simon Pickin Track 2. Lecturer: ... JPA EntityManagerFactory ... If a user is fond of a

Rich Internet Applications aim to provide the best user experience combining the best from three different worlds:

As Desktop Applications:

Provide a rich user interface.Are able to execute complicated tasks.

As web ApplicationsTheir functionality is updated on the go, without user interaction.

Little footprint.As communication technologies.

The ability to cooperate with others.The ability to join social networks with similar interests.Sharing information with others.Benefiting from other users.

3

Thanks to the ubiquitous JRE, Java FX can be executed on any platform, even the

most uncommon ones.

Java FX applications can be executed on any desktop computer, regardless of

Operating System or Browser.

As a side note, neither Linux nor Solaris are supported at the

moment.

They can also be executed on different hardware platforms, such as:

Mobile Phones.

Netbooks.

PDA.

TV.

Any future multimedia device.

4

Page 9: Sesión 2. Profesor: Simon Pickin Track 2. Lecturer: Simon ...€¦ · Sesión 2. Profesor: Simon Pickin Track 2. Lecturer: ... JPA EntityManagerFactory ... If a user is fond of a

Application Contents and Services developped with Java FX rely on:

An application framework to develop the whole project.

API for:

Desktop unique elements, such as mouse input or webcam.

Mobile unique elements, such as communications.

TV unique elements, such as recording and watching live video.

Common elements to all of the above.

These API execute in the JavaFX runtime, which is automatically downloaded

with new versions of the JRE.

Any JavaFX application can subsequently be executed on newer Java Virtual

Machines.

5

JavaFX also provides new tools for developers:

Netbeans IDE has been updated to allow maximum performance while

developing JAVAFX software.

The very popular Eclipse IDE does have a plugin to develop JavaFX

applications.

Thus, no need to change our routine!!

The syntax, however, is a bit different:

Despise the expectations of many in the Java community, the syntax is not

exactly a mix with J2EE and Javascript

The syntax does feel familiar to Java developers, but some expressions

remind of Python.

Open Sourced, although not entirely:

The JavaFX core runtime is proprietary, although free of charge.

The JavaFX compiler and plug-in are Open Source under GPLv2 license.

There are plans to open source all possible code, except third parties' code.

this new tool and benefit from what the community can bring.

6

Page 10: Sesión 2. Profesor: Simon Pickin Track 2. Lecturer: Simon ...€¦ · Sesión 2. Profesor: Simon Pickin Track 2. Lecturer: ... JPA EntityManagerFactory ... If a user is fond of a

JavaFX, of course, does also provide new tools for designers.

Plugins for well know design software, such as Adobe Illustrator and

Photoshop.

Yes, those applications are from the competition!! And not from any

competition, but the incumbent.

No plugins for animated graphics tools, which could turn to be a huge

problem.

Meaning the same software package cannot be used for programming and

designing an application.

The workflow is thus very similar to what it was in Java applications. You code

in one place, design in another and then bring everything together.

The competition does have tools that allow developers to do everything in

one place: Adobe Flash.

7

Java FX brings:

Ease of access to well known application from any device.

If a user is fond of a certain application on his desktop computer, he

Software and Hardware are not tied in any way, bought software

could be profited from any device, not only the one where we installed

it.

Weak Performance.

Applications run on JVM, which in turn runs on the native hardware.

Native applications will run faster and smoother -

AppStore.

JavaFX is so slow, that in their video demonstration website they use

8

Page 11: Sesión 2. Profesor: Simon Pickin Track 2. Lecturer: Simon ...€¦ · Sesión 2. Profesor: Simon Pickin Track 2. Lecturer: ... JPA EntityManagerFactory ... If a user is fond of a

JavaFX has to confront several competitors all at once:

Microsoft Silverlight is also cross platform, or at least aims to be, and

intergrates in the .NET framework environment. It is, however, a lot more

expensive.

Adobe Flex, Apollo, Air and other projects from Adobe try to bring Rich

Adobe Flash, the unexpected king of Internet Applications. Initially designed

to create animated cartoons and graphics to deploy over the Internet, it

quickly became the defacto standard for Rich Internet Applications, such as

Youtube

rivaled by that of the JRE. Adobe Flash has however many weak points, such

as a not too friendly development environment and too big a footprint on

mobile devices.

9

Does Java

SuN

No linux nor solaris.No mobile phone.No TV.

platform. Even Flash can be executed in more devices.It has very poor performance.

On the JavaFX users can try out several demo applications.Even these simple applications take a lot of time to load

The execution is far from smooth.On the video part of the site, where JavaFX keynotes are, they

use Adobe Flash, that is their competitors product. If even they

On the upside:The JRE is installed in hundreds of millions of desktop computers as

well as smartphones and handhelds.Developing for JavaFX is fast to learn if you already know Java and

10

Page 12: Sesión 2. Profesor: Simon Pickin Track 2. Lecturer: Simon ...€¦ · Sesión 2. Profesor: Simon Pickin Track 2. Lecturer: ... JPA EntityManagerFactory ... If a user is fond of a

11

Page 13: Sesión 2. Profesor: Simon Pickin Track 2. Lecturer: Simon ...€¦ · Sesión 2. Profesor: Simon Pickin Track 2. Lecturer: ... JPA EntityManagerFactory ... If a user is fond of a

Contenido

¿Que es?HistoriaBreve descripciónCaracterísticas

Ventajas y puntos fuertesDesventajas y limitaciones

DesarrolloRuby on Rails

¿Que es?PrincipiosArquitectura MVCComponentes de RailsSoporte de servidores webEjemplo de Aplicación

Uso de Ruby y on RailsConclusionesReferencias

¿Qué es?

Es un lenguaje de programación interpretado , reflexivo, orientado a objetos y con un balance cuidado.

Historia

2006: Reconocimiento masivo grupos activos.2007: versión 1.8.6 1.9.0Rendimiento diferente diferentes maquinas virtuales:

- JRuby.- Rubinius.

TIOBE posiciona a Ruby en la posición 13 del ranking mundial.

RUBY

Viene de

- Perl - Python

Lo

- Groovy on Grails

De Perl (perla) Ruby (rubí), de Ruby on Rails Groovy on Grails

RUBY

Page 14: Sesión 2. Profesor: Simon Pickin Track 2. Lecturer: Simon ...€¦ · Sesión 2. Profesor: Simon Pickin Track 2. Lecturer: ... JPA EntityManagerFactory ... If a user is fond of a

Featuresof Ruby

GarbageCollector

Familiar Syntax

Open Source

ObjectOriented

Single Inherita

nce

DynamicTyping

Breve descripciónExplicación de las principales características (I)

Breve descripciónExplicación de las principales características (II)

Ejemplo de tipos dinámicos

Java (sin tipo dinámico)

int[ ] a = {1,2,3};

Ruby

a = [1,2,3]

manejo de excepciones

altamente portable

hilos de ejecución simultáneos (green threads)

carga Librerías ( Estándar, DLL y Lib compartidas)

se interpreta: sin compilador

introspección, reflexión y metaprogramación

inyección de dependencias

alteración de objetos en tiempo de ejecución

redefinición de operadores (sobrecarga)

Breve descripciónExplicación de las principales características (III)

Ejemplo redefinición de operadores

class Numeric

def sumar(x)

self.+(x)

end

end

y = 5.sumar 6

Breve descripciónExplicación de las principales características (IV)

Page 15: Sesión 2. Profesor: Simon Pickin Track 2. Lecturer: Simon ...€¦ · Sesión 2. Profesor: Simon Pickin Track 2. Lecturer: ... JPA EntityManagerFactory ... If a user is fond of a

Fácilmente integrable (en módulos)

Flexibilidad

Simplicidad (hacer más con menos)

Cercano al lenguaje natural

Productividad

Principio de menor sorpresa

Cambio de paradigma:

humano al servicio de la máquina a la máquina al servicio del

Breve descripciónVentajas y puntos fuertes (I)

# Ruby knows what you mean,

#even if you want to do math on

# an entire Array

cities = %w[ London

Oslo

Paris

Amsterdam

Berlin ]

visited = %w[Berlin Oslo]

puts "I still need " +

"to visit the " +

"following cities:",

cities - visited

Ejemplo de simplicidad

Breve descripciónVentajas y puntos fuertes (II)

Tipos dinámicos problemas inesperados

Metaprogramming Monkey patching

Hilos green threads

Sin soporte Unicode

Problemas de compatibilidad hacia atrás

Ruby más lento

Ruby 2.0 llega a resolver:

Hilos green threads

Problemas sin resolver:

Falta especificación ( ¿Especificación ISO?)

Breve descripciónDesventajas y limitaciones

Dos maneras de programar en Ruby:

Interprete IRBArchivo .rb

¿Cómo desarrollar?

Módulos predefinidos: módulo.método(parámetros) Math.sqrt(9).

Definición de variables y métodos: a = 3 ** 2Delimitadores de instrucción (;).#Comentario de una sola línea=begin Esto es un comentario de varias líneas =end

Desarrollo

Page 16: Sesión 2. Profesor: Simon Pickin Track 2. Lecturer: Simon ...€¦ · Sesión 2. Profesor: Simon Pickin Track 2. Lecturer: ... JPA EntityManagerFactory ... If a user is fond of a

#!/usr/bin/env ruby

Class MegaAnfitrionattr_accessor:nombres

def initialize(nombres = "Mundo")@nombres = nombres

end

def decir_holaif @nombres.nil?

puts "..."elsif @nombres.respond_to?("each")

@nombres.each do |nombre|puts "Hola #{nombre}"

endelse

puts "Hola #{@nombres}"end

end

def decir_adiosif @nombres.nil?

puts "..."elsif @nombres.respond_to?("join")puts "Adiós #{@nombres.join(", ")}.

Vuelvan pronto."else

puts "Adiós #{@nombres}. Vuelva pronto."

endend

end

Desarrollo

if __FILE__ == $0ma = MegaAnfitrion.newma.decir_holama.decir_adios

Pablo"ma.decir_holama.decir_adios

ma.nombres = Javi Ruben", Celia",

Juan Alvaro"]ma.decir_holama.decir_adios

ma.nombres = nilma.decir_holama.decir_adios

end

Hola MundoAdiós Mundo. Vuelve pronto.

Hola DiegoAdiós Diego. Vuelve pronto.

Hola JaviHola RubénHola CeliaHola JuanHola ÁlvaroAdiós Javi, Rubén, Celia, Juan, Álvaro. Vuelvan pronto.

...

...

Desarrollo

Page 17: Sesión 2. Profesor: Simon Pickin Track 2. Lecturer: Simon ...€¦ · Sesión 2. Profesor: Simon Pickin Track 2. Lecturer: ... JPA EntityManagerFactory ... If a user is fond of a
Page 18: Sesión 2. Profesor: Simon Pickin Track 2. Lecturer: Simon ...€¦ · Sesión 2. Profesor: Simon Pickin Track 2. Lecturer: ... JPA EntityManagerFactory ... If a user is fond of a

Se encuentra en un momento de gran éxito

Simulación:NASA Langley Research

Modelado 3D:Google SketchUp

Aplicaciones web (on Rails):

Basecamp:

Control

de proyectos

La Coctelera:Crea tu blog

43things:Consigue tus metas

en la vida

ODEO:Graba y comparte

audio

Uso de Ruby y on Rails

Redes:Open Domain Server

Telefonía:Lucent 3G

Tecnología útil, de fácil implementación.

Su éxito radica en la rapidez de sus aplicaciones.

Planteamiento distinto al resto de tecnologías.

Aprendizaje más rápido que en otros lenguajes.

En expansión.

No se dispone de mucha documentación al ser relativamente nuevo.

Conclusiones

http://www.ruby-lang.org/es/http://es.wikipedia.org/wiki/Rubyhttp://www.demiurgo.org/src/ruby/http://www.ruby-lang.org/es/documentation/quickstarthttp://rubytutorial.wikidot.comhttp://meshplex.org/wiki/http://rubyargentina.soveran.com/http://www.rubycentral.com/http://www.artima.com/intv/ruby.htmlhttp://www.informit.com/articles/article.aspx?p=18225http://en.wikipedia.org/wiki/Ruby_on_Railshttp://www.meshplex.org/wiki/Ruby/Ruby_on_Rails_programming_tutorialshttp://www.slideshare.net/vishnu/workin-on-the-rails-roadhttp://guides.rubyonrails.org/getting_started_with_rails.htmlhttp://www.hackerdude.com/courses/rails/PrimeraAplicacion.htmlhttp://tryruby.hobix.com/

Referencias

Page 19: Sesión 2. Profesor: Simon Pickin Track 2. Lecturer: Simon ...€¦ · Sesión 2. Profesor: Simon Pickin Track 2. Lecturer: ... JPA EntityManagerFactory ... If a user is fond of a
Page 20: Sesión 2. Profesor: Simon Pickin Track 2. Lecturer: Simon ...€¦ · Sesión 2. Profesor: Simon Pickin Track 2. Lecturer: ... JPA EntityManagerFactory ... If a user is fond of a

Software deComunicaciones

2007-2008

Groovy / Groovy on Grails

DANIEL ACEITUNO GOMEZ – NIA: 100061824 CARLOS ESTEBAN BAZ HORMIGOS – NIA: 100061836

FRANCISCO JAVIER MARTINEZ MENCIAS - NIA: 100048562 DIEGO JOSE PEREZ GONZALEZ – NIA: 100048615

Departamento de Ingeniería Telemática Universidad Carlos III de Madrid

2

Software deComunicaciones

2007-2008 2

Contenido

• Introducción

• Groovy

• Grails

• ¿Cómo crear un proyecto en Grails?

• Referencias

3

Software deComunicaciones

2007-2008

Introducción

• Groovy es un lenguaje dinámico ejecutable en una JVM no interpretado (hay que compilar)

• Ventaja: su sintaxis es compatible con Java, pero añade funcionalidades y atajos que ahorran muchas líneas de código.

• Grails es un framework para desarrollar aplicaciones web siendo uno de sus pilares Groovy.

• Ventaja: Permite crear muy rápidamente, sin apenas desarrollar código, aplicaciones web especialmente de tipo CRUD (Create, Read, Update, Delete)

3 4

Software deComunicaciones

2007-2008

Groovy

• Cualquier clase/objeto Java es un clase /objeto Groovy.

• Sintaxis:

No hace falta poner return en los métodos que devuelven algo (se devuelve directamente lo que de la última línea)

Los paréntesis al llamar a un método son opcionales

El ';' al final de cada sentencia también es opcional

No existen tipos primitivos: los objetos y métodos se crean con def

Closures: Bloques de código reusables (similar a cómo se define una función anónima en JavaScript)

4

Page 21: Sesión 2. Profesor: Simon Pickin Track 2. Lecturer: Simon ...€¦ · Sesión 2. Profesor: Simon Pickin Track 2. Lecturer: ... JPA EntityManagerFactory ... If a user is fond of a

5

Software deComunicaciones

2007-2008

Groovy (2)

Dos tipos básicos de datos, además de los de Java: listas (son en el fondo java.util.ArrayList ) y mapas (java.util.HashMap)Expresiones regulares: En Groovy basta con declarar la expresión de búsqueda entre barras diagonales, como en Perl, y usar uno de los tres operadores disponibles:

=~ búsqueda de ocurrencias (produce un java.util.regex.Matcher)==~ coincidencias (produce un Boolean)~ patrón

• Ejemplo:def texto = "Groovy es un lenguaje dinámico"

assert texto =~ /ua/

Esta expresión devolvería true porque la frase contiene “ua”(assert es donde se guarda el resultado de expresiones lógicas)

6

Software deComunicaciones

2007-2008

Groovy (3)

• Se pueden redefinir operadores

• POGO’s: Este objeto tiene una utilidad parecida a los beans de Java. Se define un tipo de datos y se utiliza para acceder a los atributos de una instancia

Ejemplo: class Persona {String nombreString apellidoprivate int id

String toString() { "${nombre} ${apellido}" }def getNombreCompleto() { "${nombre} ${apellido}" }

}

6

7

Software deComunicaciones

2007-2008

Grails

• Es un framework para desarrollo de aplicaciones web construido sobre cinco fuertes pilares:

1. Groovy, para la creación de propiedades y métodos dinámicos en los objetos de la aplicación

2. Spring, para los flujos de trabajo e inyección de dependencias

3. Hibernate, para la persistencia4. Sitemesh, para la composición de la vista5. Ant, para la gestión del proceso de desarrollo

• Desde el punto de vista del diseño, Grails se basa en los principios "Convención mejor que configuración" y DRY ("No te repitas")

8

Software deComunicaciones

2007-2008

Grails (2)

• No necesitamos servidor adicional ni base de datos, aunque podemos usarlos si tenemos alguno: Grailsincorpora Jetty y HSQLDB "de serie", con lo que tenemos una base de datos y servidor de desarrollo sin tener que montarlo nosotros

• No hacen falta getters ni setters: Groovy los genera dinámicamente por nosotros

• ¿Qué más nos permite?:

Introducir AJAX en nuestras aplicaciones

Más rápidez y más sencillez que JavaScript

Page 22: Sesión 2. Profesor: Simon Pickin Track 2. Lecturer: Simon ...€¦ · Sesión 2. Profesor: Simon Pickin Track 2. Lecturer: ... JPA EntityManagerFactory ... If a user is fond of a

9

Software deComunicaciones

2007-2008

¿Cómo crear un proyecto en Grails?

1. Se define un tipo de datos, por ejemplo, usuario:class Usuario{String nombreString apellidos}

2. Al compilar, se genera todo, desde el HTML del formulario de entrada hasta el equivalente a nuestro “DBConnector” y la propia base de datos.

10

Software deComunicaciones

2007-2008

Referencias

• Groovy: http://groovy.org.es/home/story/introduccioacuten-a-groovy

http://groovy.org.es/home/story/99

http://groovy.org.es/home/story/introduccioacuten-a-groovy-parte-3

• Groovy on Grails:

http://groovy.org.es/home/story/52

http://groovy.org.es/home/story/56

http://groovy.org.es/home/story/59

http://grails.org/

http://grails.org/Ajax

Page 23: Sesión 2. Profesor: Simon Pickin Track 2. Lecturer: Simon ...€¦ · Sesión 2. Profesor: Simon Pickin Track 2. Lecturer: ... JPA EntityManagerFactory ... If a user is fond of a

Jakarta Struts

���������

��� ����������

���������

Alejandro Martínez Azpiri

Bachir Kayali Lucena

Jorge Nogales Blanco

Laura Fernández Villar

Departamento de Ingeniería Telemática

Universidad Carlos III de Madrid

Introducción

• Servlets Java mejores que CGI estándar.

• JavaServer Pages (JSPs) permiten escribir Servlets

dentro de ellas, aunque tienen problemas de control de

flujo.

• JSPs y servlets juntos:

���������

��� ����������

���������2

JSPs y servlets juntos:– Servlets � el control de flujo

– JSPs � escribir HTML.

• Arquitecturas

– Model-1: Modelo y Vista + Controlador

– Model-2: Modelo, Vista y Controlador

2

MVC: Modelo Vista Controlador

���������

��� ����������

���������33

¿Qué es struts?

• “Estructura de soporte para el desarrollo de

aplicaciones web que implementa el patrón MVC en

Java”.

• Define la jerarquía de clases genéricas y su

funcionalidad.

���������

��� ����������

���������4

funcionalidad.

• Eje central � descriptor (XML).

• Controlador (ActionServlet) analiza el descriptor para

utilizar un manejardor de peticiones (Action y

ActionForm).

• Vista generada por Tags.

• Validacion de datos de entrada (ActionForm).

4

Page 24: Sesión 2. Profesor: Simon Pickin Track 2. Lecturer: Simon ...€¦ · Sesión 2. Profesor: Simon Pickin Track 2. Lecturer: ... JPA EntityManagerFactory ... If a user is fond of a

Vista

• Muestra el resultado de las peticiones.

• Compuesto por JSP´s.

• Tags: desaparece el código Java <%...%>• <html:base>

• <html:button>

���������

��� ����������

���������5

html:button

• <html:checkbox>

• <html:errors>

• Internacionalización.

Control

• Procesa la solicitud de un usuario � Genera una

respuesta � Cede el control a la vista.

• Clase Action: procesar una solicitud (perform()) � objeto

ActionForward �JSP

St t fi l

���������

��� ����������

���������6

• Struts-config.xml:

• <form-beans>

• <action-mappings>

Modelo

• Representación específica de la información con la

cual la aplicación opera.

• Clase ActionForm: JavaBean encargado de las

comprobaciones y la gestión errores en formularios

HTML.

���������

��� ����������

���������7

Esquema General

���������

��� ����������

���������8

Page 25: Sesión 2. Profesor: Simon Pickin Track 2. Lecturer: Simon ...€¦ · Sesión 2. Profesor: Simon Pickin Track 2. Lecturer: ... JPA EntityManagerFactory ... If a user is fond of a

Struts 2

• Fruto de la unión de Struts con otro frameworkdenominado WebWork.

• Mejoras:– Facilitar el despliegue de aplicaciones.

– Diseño mejorado.

���������

��� ����������

���������

Diseño mejorado.

– Nuevos tags.

– Soporte para AJAX.

– Integración sencilla para Spring.

– Formularios POJO (olvídate de los ActionForm).

– Añadir plugins fácilmente.

– Reporte de errores más preciso.

– Integración de herramientas de debbuging.

– Añadir nuevos tags fácilmente.

9

Conclusiones

• Clara separación Modelo-Vista-Controlador y

simplificación.

• Canalización de peticiones.

• Fin del código Java en HTML (Tags).

���������

��� ����������

���������

g ( g )

• Permite desarrollo en paralelo.

• Potencia la reutilización.

• Soporte de múltiples interfaces de usuario e

idiomas.

• Java � Open Source � multiplataforma.

10

Preguntas

���������

��� ����������

���������11

Page 26: Sesión 2. Profesor: Simon Pickin Track 2. Lecturer: Simon ...€¦ · Sesión 2. Profesor: Simon Pickin Track 2. Lecturer: ... JPA EntityManagerFactory ... If a user is fond of a
Page 27: Sesión 2. Profesor: Simon Pickin Track 2. Lecturer: Simon ...€¦ · Sesión 2. Profesor: Simon Pickin Track 2. Lecturer: ... JPA EntityManagerFactory ... If a user is fond of a
Page 28: Sesión 2. Profesor: Simon Pickin Track 2. Lecturer: Simon ...€¦ · Sesión 2. Profesor: Simon Pickin Track 2. Lecturer: ... JPA EntityManagerFactory ... If a user is fond of a