Web Frameworks

Java is a great language, but if you have ever tested any scripting language like PHP, Ruby, node.js, you know Java is… Over Engineered.

You have to write lots of code for anything. Big configuration files, use of application servers, too many classes to perform simple tasks, no support for Collections literals, etc…

Because of that, and before I knew the world beyond java, I started Blaapps (Bery Lol AAplication Server). A very lightweight application server minded for speed up development of web apps.

After I presented it as my final year project I stopped developing new features, but recently I had to do some web stuff on java and I remembered how painful it is.

If you start doing a web project with java, you feel naked. Standard tools are bare minimum. That’s why there’s a lot of web frameworks for JavaEE.

But most of them follow the java over engineering philosophy. Let’s see some examples…

Installation

Let’s see what is needed to develop with some of the main web technologies:

Technology Base Testing server Dependency Management
Java EE Java Runtime + IDE Application Server maven, not included
Play Framework Java Runtime + Play Embedded server included commands
PHP PHP Embedded server pear – Included
Ruby On Rails Ruby + Rails Embedded server Ruby Gems, not included
Node.js Node.js Embedded server npm – Included

So, if you want to develop a Java EE web app, you will have to download the JRE, an application server, and the Java framework you want to use. Also, you will need an IDE, as the Java language requires you to write lots of code, and compiling processes aren’t simple.

So, if you want to develop a Java EE web app, you will have to download about 500MB. ¡WTF!

Node.js download is 7,7MB.

Hello world

Let’s see how to write a Hello World app in different platforms:

Java EE

You need the following files:

  • index.jsp
  • WEB-INF/web.xml

The WEB-INF/web.xml would be like this:

<?xml version="1.0" encoding="UTF-8"?>
 
<web-app
        version="3.0"
        xmlns="http://java.sun.com/xml/ns/javaee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
  <display-name>Hello World</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
</web-app>

And the index.jsp:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<html>
  <head><title>Hello World</title></head>
  <body><h1>Hello World</h1></body>
</html>

Zip them on a file named helloworld.war and copy them to the application server… ¡Super easy!

Play Framework

First, create the play project:

 $ play new helloworld

This creates lots of files.

Then, edit the main route helloworld/app/controllers/Application.java (configurable):

package controllers;

import play.*;
import play.mvc.*;

import views.html.*;

public class Application extends Controller {
  
  public static Result index() {
    return ok("Hello World!");
  }
  
}

Run:

 $ play
 [helloworld] $ run

And you will see the app on localhost:9000

PHP

Write an index.php:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<html>
  <head><title>Hello World</title></head>
  <body><h1>Hello World</h1></body>
</html>

and run:

 $ php -S localhost:8000

Your app is on localhost:8000

Ruby on rails

Like play, we have to create a project first:

 $ rails new helloworld
 $ cd helloworld
 $ rails server

That will start the new project and a server on localhost:3000

To edit the index, remove the default index and create a route:

 $ rm public/index.html
 $ rails generate controller home index

Edit config/routes.rb to add:

root :to => "home#index"

Edit app/views/home/index.html.erb to be:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<html>
  <head><title>Hello World</title></head>
  <body><h1>Hello World</h1></body>
</html>

And that's all! Almost easier than Java!

Node.js

write a new file named app.js:

var http = require('http');
var requestListener = function (req, res) {
  res.writeHead(200);
  res.end('Hello, World!\n');
};

var server = http.createServer(requestListener);
server.listen(8080, "127.0.0.1");

run:

 $ node app.js

And you are ready! Your app will be on localhost:8080.

Conclusion

There are lots of Web frameworks out there, and Java is not the only way of doing things.

Choose your framework thinking in what's important for you. For me it's:

  1. Fast Development
  2. Fast Deployment
  3. Huge community

I want to start developing fast. One way of reading it is the lack of need for an IDE. If you need an IDE to help you, it's not simple enough.

Also the lack of a framework is important. With Java EE you will need to add a framework, it's another layer of complexity. The more layers, the more things that can go wrong.

Ruby on rails is a framework by itself, but hey! You need commands to create correctly new files. There's too much dark magic in ruby on rails…

Make it simpler!

Same could be applied to deployment. If I can't just copy the files to the server, it's not simple enough.

Also, a huge community ensures you that you'll have lots of plugins and libraries ready.

Of course, my option right now is Node.js.

Acertijo Java (Solución)

A principios de mes proponía un Acertijo Java.

¿Qué sale por pantalla al ejecutar la clase FooBar?

import static java.lang.System.*;
public class FooBar {
  public FooBar() {
    out.print(" Instance ");
  }
  static {
    out.print(" Static ");
  }
  public static void main (String args) {
    out.print(" Main ");
    new FooBar();
  }
}

Simplificando, lo que ocurre es lo siguiente:

  1. Se carga la clase FooBar en memoria
  2. Se ejecutan los bloques estáticos: static{}
  3. out.print(» Static «); está en un bloque estático
  4. Una vez cargada la clase, ya se pueden ejecutar métodos estáticos como main
  5. out.print(» Main «); está dentro del método main
  6. Se crea una instancia de la clase FooBar en el método main
  7. Para ello se ejecuta el constructor
  8. out.print(» Instance «); está en el constructor

Siguiendo este razonamiento, la opción correcta sería la c: «Static Main Instance».

La opción c parece correcta, pero no se llega a ejecutar el método main. Recordemos la firma que tiene que tener el método main para ser la entrada de un programa java:

  public static void main (String[] args) {}

Ha de ser esa o equivalente. ¿Ves la diferencia? El parámetro args tiene que ser un array [] de String, ya que representa los argumentos introducidos por línea de comandos. En la clase FooBar el parámetro args es simplemente un String.

Por ello, el código no se ejcutará. Java mostrará un error indicando que en la clase FooBar no existe un método main. Es por ello que la opción correcta era la f: No se ejecutará

En el día a día, un programador no sólo tiene que saber traducir ideas a código. En algunas ocasiones el código no se comporta como queremos y es cuando hay que buscar el detalle.

La agilidad con la que uno detecta pequeños detalles marca la diferencia. Algunos factores que afectan a esta agilidad son, la paciencia, saber escribir código claro, y sobre todo el conocimiento de las herramientas con las que uno trabaja.

Igual que hice en el otro post, animo a cualquiera a ponerse a prueba estudiando la certificación de Programador Java o acudir a uno de los cursos oficiales que imparto, es toda una experiencia.

Acertijo Java

Volvemos después de la resaca de año nuevo con un acertijo java.

Suponiendo que el contenido del archivo FooBar.java es el siguiente… ¿Qué saldrá por pantalla al ejecutar la clase FooBar?


import static java.lang.System.*;
public class FooBar {
  public FooBar() {
    out.print(" Instance ");
  }
  static {
    out.print(" Static ");
  }
  public static void main (String args) {
    out.print(" Main ");
    new FooBar();
  }
}
  • Main Static Instance
  • Instance Static Main
  • Static Main Instance
  • Main Instance
  • No compilará
  • No se ejecutará

Hagan sus apuestas…

Antes de empezar a preparar la certificación SCJP (Sun Certified Java Programmer) no había caído en la cuenta de cuántas cosas desconocía de programación.

Estés preparando o no la certificación de programador, recomiendo la guía de Kathy Sierra. Además, si quieres que un experto en java (modestia aparte) te asista, puedes invitarme a tomar una cerveza, o apuntarte al curso oficial que impartiré en septiembre: SL-275-SE6 Java Programming Language

¡Date prisa, al tercero que me invite a una cerveza ya no hablaré coherentemente, y el curso tiene las plazas limitadas!

Un Saludo!

Actualizado: Puedes encontrar la solución aquí.