Friday, February 5, 2010

Annotated Dynamic Titles

Web applications usually have two parts in their title. One indicating the current page and the other describing the entire application. It would be nice to put the application wide title and parameterize the page level title within your applications' layout. Starting from 0.5, EasyWeb4J allows you to annotate your action methods with custom annotation and access them easily within any part of your controller.

This sample application would have two pages with titles "Home - Dynamic Title Demo" and "Admin - Dynamic Title Demo". Here, "Home" and "Admin" are specific to the particular page while the rest of the title is common to the entire application.


Download the complete source code for this application.

Layout and Controller

The layout specifies the application wide title as template text and uses an EL expression to include the page specific title before it. It also provides the navigation links for the 2 pages.

src/main/webapp/WEB-INF/layouts/Application.jsp


The controller has 2 actions corresponding to the application's pages.

src/main/java/org/title/controllers/HomeController.java


Making it Work

Let's create a custom annotation specific to this application which will be used on the action methods to specify the page specific title

src/main/java/org/title/annotations/Title.java


Next, we must override the filterRequest() method to make use of the Title annotation when available on action methods. EasyWeb4J 0.5 and above provide the getActionAnnotation() method, which can be used in our filter to access the annotations on the current request's action method.

We then annotate our action methods with @Title("Home") and @Title("Admin") to specify their titles as shown below.

src/main/java/org/title/controllers/HomeController.java


In a real-world application the filter can be moved to an abstract super class to setup the appropriate titles for actions across all controllers.

Wednesday, January 27, 2010

EasyWeb4J 0.5 Released

We're proud to announce the release of EasyWeb4J 0.5. This release includes several important changes to further simplify development of web applications using EasyWeb4J.
  1. Components of the request URL after the action name are passed to the action method as parameters. These are also converted to the appropriate basic type of the parameters. getIntegerId(), getLongId(), getStringId(), etc. need not be used any more. See the "Parameters in Action Methods" section of this tutorial page.
  2. You can define and use application-specific custom annotations on action methods. These annotations can be obtained within your controller using the getActionAnnotation() and getActionAnnotations() methods. This can be very handy to do things like action specific authorization and for setting up action specific request attributes like title, stylesheet, etc.
  3. A ResponseHandler interface is provided which can be used to generate raw responses cleanly within the view rendering transaction. See the "Generating Raw Response" section of this tutorial page. Closures should hopefully allow a lot cleaner syntax for this when Java 7 is out.
  4. Attributes of your application's ServletContext can be injected into your controllers' fields using @ContextAttribute annotation.
  5. Model class provides validateRequired() methods which can be used to validate presence of value in fields.
  6. Starting from this release EasyWeb4J will be available from its own maven repository and hence need not be installed to maven manually.
  7. The hbm2ddl.auto hibernate property is set to update when a new project is created to simplify initial development. You might want to disable this before taking your application to production.
Contributing to EasyWeb4J also got simpler as the source repository has been moved to GitHub. :)

If that caught your attention, get yourself started with the tutorial and hit the mailing list for any further assistance.


Tuesday, December 1, 2009

Simple Authentication and Authorization with EasyWeb4J

This post demonstrates the implementation of a simple password based Authentication and Authorization system built with EasyWeb4J. This post will demonstrate the hashing API of EasyWeb4J (including salt generation) and put to use EasyWeb4J's simplified request filtering for authorization.

When a user signs up his password is combined with a random salt of 10 bytes. This is then hashed using MD5 algorithm. The salt and the password hash are stored. During login the user is retrieved by his username and the entered password is hashed and compared against the original hash.

Download the complete source code for this application.

Create a new EasyWeb4J Hibernate Project as described in the tutorial. Configure hibernate as shown below.

src/main/resources/hibernate.xml

The Model

src/main/java/net/auth/models/User.java

The encryptPassword method generates a random salt and encrypts the clear text password using MD5 algorithm and the salt, using EasyWeb4J's hashing API. The matchesPassword method takes a clear text password input by the user, hashes it using the previously generated salt and compares it with the original hashed password.

The Controllers

This sample application has three controllers.
  1. UsersController - Handles user signup.
  2. SessionsController - Handles login and logout.
  3. HomeController - The actual application which needs to be secured by requiring login.
src/main/java/net/auth/controllers/UsersController.java

Not much magic there. Just a standard controller to create a user after encrypting the entered password.

Authentication

src/main/java/net/auth/controllers/SessionsController.java

This controller authenticates a user from login screen and redirects them to the secure home page after storing the user ID in session. If login fails, it redirects to the login page back after setting a message in flash. Also, while displaying the login page it checks whether the user has already logged in and if so directly redirects them to home page without requesting credentials.

Authorization

While there is only one controller in this example whose requests need to be secured, in real applications there would be several. Hence we create an abstract controller which will override the filterRequest() method to perform authorization during each request.

src/main/java/net/auth/controllers/SecureController.java

It verifies whether a user is currently logged in and if so, sets the real user as a request attribute. This would be used to greet the user by his full name.

Finally we have the home controller which in this sample does nothing other than rendering the index view.

src/main/java/net/auth/controllers/HomeController.java

There we have a complete DB based login system. :)

Monday, November 30, 2009

EasyWeb4J 0.3 is Out with Support for Cleaner URLs

After quite a long time of silence, EasyWeb4J 0.3 has been released. Some of the major changes in this release include,
  1. The "/dispatcher" part is dropped from the URLs as EasyWeb4J now uses a filter instead of a servlet for dispatching requests.
  2. An improved API for hashing with support for easy salt generation.
  3. Unified handling of both muti-database and single-database projects.
  4. A significantly improved code architecture.
This release breaks compatibility with 0.2 in few minor ways.
  1. /src/main/resources/repositories.properties must be present even for single-database projects. This file would be auto-generated when creating new projects.
  2. The "dispatcherRoot" attribute is not set anymore as it does not exist.
All previous samples in this blog have been updated to use the new version. Grab it and enjoy web development with Java!

Saturday, August 22, 2009

EasyWeb4J 0.2 Supports Multiple Databases and Simplifies Validations

We're proud to announce the release of EasyWeb4J 0.2. This release focussed on supporting multiple databases within a single application and also simplifies validations in models.

Some of the significant changes in this release include,
  1. Repository management code is re-designed to simplify support for multiple databases and to support more persistence mechanisms.
  2. Support for multiple DBs has been added to Hibernate and JPA repositories.
  3. There is just one validate method to perform all validations.
  4. Validation of basic types are handled automatically.
  5. This release also creates projects with a default message bundle to facilitate internationalization.
This release breaks compatibility with 0.1. The tutorial and all previous posts in this blog have been updated for the new version.

Download the new release and give the tutorial a shot. We're sure you'd love it. :)

Friday, July 31, 2009

Porting Rails Shoutbox to EasyWeb4J

It is a widely held belief that Java unnecessarily penalizes simple web applications. This post demonstrates that by using EasyWeb4J, you can "almost" achieve the productivity of Rails without missing Java's raw performance.

This tutorial is inspired by this article on Nettuts+. I have included the stylesheets and images from Dan's post to retain the look and feel of the final result.

Download the complete source code for this application.

Create a new EasyWeb4J Hibernate Project as described in the tutorial, with settings as shown below.

MySQL Setup

Run this script to create a database for shoutbox
Edit your pom.xml and add a dependency for MySQL JDBC driver as below.
Point Hibernate to the newly created database as below.

src/main/resources/hibernate.xml

Model


The model specifies the validations for each shout and also generates an MD5 hash of the email used in the shout.

src/main/java/org/shoutbox/models/Shout.java

Repository


Unlike Rails EasyWeb4J uses repositories to load models from database. However, for this simple app, the repository can be an empty class.

src/main/java/org/shoutbox/repositories/ShoutRepository.java

Controller


We create a separate method to load all available shouts as it is needed both in the home action and if an error occurs during shout creation. Edit web.xml and specify Shouts as the ROOT_CONTROLLER.

src/main/java/org/shoutbox/controllers/ShoutsController.java

Layout

Just like Rails, EasyWeb4J also supports layouts. To know more on EasyWeb4J layouts, see this post. We specify the top level elements and include the stylesheet in our layout.

src/main/webapp/WEB-INF/layouts/Application.jsp

View


EasyWeb4J applications use JSTL to loop through elements and errors to be displayed to the user.

src/main/webapp/WEB-INF/views/Shouts/index.jsp

Where EasyWeb4J differs from Rails?
  1. EasyWeb4J uses the Respository pattern (through Hibernate/JPA) instead of ActiveRecord for persistence.
  2. EasyWeb4J does not provide migrations as DDLs need to be optimized anyway in any non-trivial application.
  3. EasyWeb4J needs a bit of XML for config (but way less than many other Java frameworks).
  4. EasyWeb4J allows you to use standard HTML for forms fields and for referencing stylesheets by offering few convenient request parameters.
  5. And yeah, EasyWeb4J app would run way faster than the Rails version. ;)

Thursday, July 30, 2009

Highlighting and Placing Focus on Errors in EasyWeb4J

Highlighting fields with input errors is a common technique used in web applications to gain users attention to the errors. It is also helpful to place the focus on the first field with error so that the user can start correcting the input right away.

This can be implemented in an EasyWeb4J applciation by checking for the presence of error on the field of your model, represented by the input field. If an error is present, use a different CSS class for the input field which does the highlighting. To place the focus on the first field with error, you can use jQuery to select the first field with the CSS class representing errors. The completed application would look like this.

Download the complete source code for this application.

Create a new EasyWeb4J Hibernate Project as described in the tutorial. Since we do not need a database for this demo, delete src/main/resources/repositories.properties from the newly created project.

The Model

src/main/java/org/error/models/Person.java

The View

src/main/webapp/WEB-INF/views/Person/index.jsp

The view uses EL expression to determine whether an error is present on the field represented by each input. If present, it sets the CSS class of the input element to errorField.

The Javascript

src/main/webapp/js/script.js

The script places the focus on the first field with error. If none of the fields have an error in input, it places the focus on the first input field.