Architecture & DesignJavaServer Faces and ASP.NET - A Side by Side Look Part 2

JavaServer Faces and ASP.NET – A Side by Side Look Part 2 content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

In the previous article, I discussed the similarities and differences between the ASP.NET and JavaServer Faces frameworks. Two sample two applications were shown. One of the applications was developed using JSF and the other used ASP.NET. Both applications served the same functional purpose: to allow employees to reserve conference rooms. Both web applications accessed the same MySql database. I used two popular IDEs (Integrated Development Environments) to assemble the applications: Microsoft’s Visual Web Developer 2005 Express Edition (Get a copy) and Sun Microsystem’s Java Studio Creator (Get a copy). During the development process, I tried to illustrate some of the basic concepts behind each framework.

In this article, a little more functionality will be added to these applications. Then, I will present some brief comparisons of these frameworks in a number of diverse areas which are not addressed by the applications, but which are of importance to application developers. As mentioned in the last article, the goal is to provide an overview of the features behind these frameworks without delving into too deeply. With some fundamental knowledge, you can further explore on your own if you wish.

Validating Input

In the last article, database data was displayed in read-only fashion to users and user interaction was limited. Most real world applications must allow users to input data into the system. Thus, validation requirements exist for almost all applications. Currently, the two applications display a list of available rooms and allow users to display any reservations associated with those rooms. A link accompanies each room which directs users to an online form where new reservations ca be made. The reservation forms for both applications are displayed below.

ASP.NET Reservations Form
JSF Reservations Form

In these forms, the user first enters a name of an individual or group that wants to make the reservation. Then, the user enters a start and end time for the new reservation. As a developer, you must account for all of the possible actions a user might take that do not conform to what the application expects. ASP.NET and JSF both provide components to help with input validation. ASP.NET Validator Controls are attached to the relevant form item and validate that item’s data upon form submission. ASP.NET Validator Controls include RequiredFieldValidator, RegularExpressionValidator, RangeValidator, and CompareValidator. A CustomValidator component can also be used when the developer needs to write custom code in order to properly validate a component. In an ASP.NET Page’s lifecycle, validation will occur, with the exception of CustomValidator, prior to the data being posted back to the server. This is because ASP.NET Validator Controls generate the necessary JavaScript needed to implement validation on the client side, thereby reducing server load. However, ASP.NET always performs this validation on the server as well to ensure validation always takes place.

JSF also provides some standard validation components, though not as numerous as the selections available in ASP.NET.
To write your own validation logic, you can also override a JSF component’s validate method or delegate validation to another class that implements the Validator interface. (You could also write your own validation component, but this is a more complex solution). JSF lacks the built-in JavaScript functionality that ASP.NET validation components offer. Validation in a JSF page takes place on the server after the component tree has been restored, but before any event handlers are called. Of course, you can always provide your own custom JavaScript validation. Given this overview, let us look at how a user’s reservation data in each of these applications can be properly validated.

These forms are fairly simple as web forms go but there are still validation issues to consider. For starters, it would make little sense to allow a user to reserve a room and not enter a name specifying who is making the reservation. Therefore, the ‘Reservation Team’ field should be required. In ASP.NET this is done by dragging a RequiredFieldValidator control from the palette onto the form. The ControlToValidate property should read ‘lblReserveTeam’. In the property palette you can specify the error text that the user should receive. I added the following error message : ‘You must enter a Reservation Team.’ The corresponding JSF Text Field component representing the reservation team does not require a separate validation component because this component already contains a property called ‘required’. Simply checking this attribute will force the user to enter a value.

Next, you can limit the length of text in the ‘Reservation Team’ field. If you remember, the corresponding database field is only 45 characters in length. Therefore, the user should be limited to entering 45 characters or less. In the JSF application, a LengthValidator component can be dragged from the ‘Validators’ section of the component palette onto the field and specify 45 as its maximum length. For its error text property, type ‘Reservation Team cannot exceed 45 characters’. ASP.NET has no standard validation control to restrict field length. Instead, you can rely on the RegularExpressionValidator control which allows the maximum length to be specified via a regular expression like ‘^[sS]{,45}$’.

The start and end times should be checked to make sure that the start time is equal to or less than the end time. ASP.NET provides a CompareValidator that will work in most cases when comparing two fields. However, since the out of the box Calendar component is being used, you cannot do this as the CompareValidator does not support this component. In this particular instance, I had to assign these dates to two text fields and validate against them instead. Another option would be to write validation logic in the Page_Load event routine itself. Since JSF has no standard validation component to compare two fields, I had to write validation logic by implementing the start time component’s validate method:

   public void calendarStart_validate(FacesContext fc, UIComponent uic, Object o) {
      if (this.calendarStart.getSelectedDate().after(this.calendarEnd.getSelectedDate()) ) {
  	     throw new ValidatorException(new FacesMessage
           ("The start time must come before the end reservation time."));

You’ll notice the reference to a FacesMessage component in the JSF validation logic above. In JSF, a message component is required to display output text related to a field. To do this, I added a Message component from the component palette and attached it to the correct form field by dragging it onto the field. Once this is complete, error messages will be displayed for the offending component when validation fails. In ASP.NET, you don’t have to perform this step because the controls themselves display the error message.

Another important set of JSF components are known as ‘converters’. These components are responsible for converting form data to and from the object model. There are a number of default converters available in JSF to perform common conversion like Strings to Integers and Strings to Dates. For more complex transformations that involve application objects, custom converters can be created. As you can see in the code above, the JSF calendar component has a method called getSelectedDate. This is because this component includes its own converter already. Though this JSF application will not require the use of converters, you should familiarize yourself with JSF converters as they can help reduce code and runtime conversion errors. ASP.NET does not provide a standard set of converters.

There is one additional validation that should probably be added to these forms. This validation would query the database to ensure there are no existing reservations that conflict with the time the user selects. To do something of this complexity, you would use a CustomValidator control in ASP.NET. Likewise, in JSF, this logic would be placed in the component’s validate method or delegated to another class that handles validations.

Adding ASP.NET Validator Controls
Adding JSF Validator Components

Internationalizing Applications

Internationalization, or i18n, is it as commonly known, refers to supporting diverse language and cultures in your application. This includes providing localized text messages and formats for items such as dates so that users in different parts of the world will view your web page in a format and language they can understand. With the worldwide growth of the web, this type of functionality becomes increasingly important. We will quickly look at how each framework allows you to externalize page text, such as field labels, to provide support for different locales.

JSF applications that support different locales do so in much the same way as other J2EE applications, by storing localized text in a resource bundle properties file. You will have one properties file for each locale that you support, with each locale identified by a language code and a country code, for example ‘en-US’. Switching the displayed language becomes a matter of redirecting to another properties file. In previous releases, supporting different locales in an ASP.NET application was no trivial task, however, there have been big improvements in this area with ASP.NET 2.0. For example, recompilation is no longer necessary when switching locales in ASP.NET 2.0.

To enable the JSF application to support different locales, I added a file to the application and added a locale for en-US. The title of the reservations page reads ‘Make a Reservation for Conference Room.’. I simply added a key/value in this resource bundle properties file:

# Sample ResourceBundle properties file
ReserveRoomTeamLabel=Reservation Team:

I could create any number of locale-specific messages for the same component. Then, I need to tell the application how to use this file by adding the following to the faces-config.xml file:

      <!--Add other locales here.-->

Referencing a resource bundle, you can substitute literal text in the JSF markup with a reference to this key. Here is an example:

<ui:label binding="#{ReserveRoom.lblReserveTeam}" id="lblReserveTeam" style="left: 48px; top: 96px; position: absolute" text="#{messages.ReserveRoomTeam}"/>

ASP.NET provides support for different locales with resource files. These resource files have an extension of .resx. ASP.NET 2.0 introduces resource expressions that you can put in ASP.NET markup. These expressions look similar to ASP.NET data binding expressions. It is possible to specify both local and global resources for an application. In this example, a local resource file is set up that pertains to only the new reservations page.

Local resources need to be placed in a folder called ‘App_LocalResources’. Each file in this folder should have a name like ‘{aspx page name}].aspx.resx’. I created a file called ‘Reservations.aspx.resx’. In it, I added an entry for ‘Reservation Team:’ just as I did in the JSF application. For the page to access this resource and assign the label the appropriate text at runtime, you could add the following expression:

<asp:Label ID="Tea" runat="server" Text=<%$ Resources:ReservationsTeamLabel %>></asp:Label>
ASP.NET – Adding Localized Text
JSF – Adding Localized Text

If you have yet to develop an application with i18n requirements, there is a strong likelihood that you will in the future. Both JSF and ASP.NET make this task easy.

Additional Topics

Finally, there are some diverse, but important, topics with regards to the JSF and ASP.NET frameworks that should be reviewed. I have attempted to provide some useful links for you where you can learn more.

Application Security

The JSF specification does not address security per say. Instead, the same options available to you when securing J2EE applications can be used with JSF. The possibilities here are numerous, well-documented, and mature. ASP.NET offers numerous security options as well. A lot of ASP.NET security is tied to the Windows platform, as you might have guessed. For example, an ASP.NET application running on an intranet can easily authenticate users based upon their Windows domain logon information. There are a number new ‘Login Controls’ in ASP.NET 2.0 to enable you to quickly add things like login forms to your applications.

Error Handling and Debugging

Once again, when developing with JSF, all the same error handling and debugging techniques available to all J2EE application developers are available to you. This includes specifying global error pages for applications, specifying specific actions based upon the HTTP error code, and more. You can log application errors and general activity using a logging mechanism such as the standard Java logging package or the popular Apache Log4j package.

ASP.NET allows you configure a lot of an application’s error handling details through the IIS server console. Also, ASP.NET provides handy tracing functionality so you can log certain types of information about a page request. Here is a good resource that provides an introduction to ASP.NET error handling.


It is often advantageous to separate out portions of a web page that are common across several different pages so that content can be reused and markup does not have to be duplicated. Application headers and footers are the best examples of page sections you will reuse across your web site. Templating encourages you to define a ‘template’ page which you use to substitute only the content that changes from page to page, leaving the rest the same. JSF provides no built in support for templating. A popular approach to templating with J2EE web applications is the Struts Tiles project. Tiles can be used with JSF too. Java Studio Creator, as well as other JSF tools, provides its own support for reusing page content. A tutorial on how to reuse page content with Studio Creator can be found here.

ASP.NET 2.0 introduces its own templating mechanism that you can use to factor out common interface sections. This feature is called Master Pages. Master Pages are a welcome introduction to the framework and I would expect the next major release of JSF to provide something similar.

Styles and Themes

Professional web developers have long used Cascading Style Sheets as a way to separate appearance styles of a page so the look and feel of a web page can be modified without editing the page markup. A ‘Theme’ can be thought of as a group of related styles. You can continue to use Cascading Style Sheets in JSF and ASP.NET. However, ASP.NET 2.0 introduced support for Themes and Skins. A ‘Skin’ is a defined style for a particular type of control. While the JSF specification does not address themes, several tools, including Java Studio Creator, provide non-standard support for themes.

About the Author

Michael Klaene is a Senior Consultant with Sogeti LLC. He has spent over 9 years in Information Technology and is an experienced Systems Analyst, delivering solutions that involve numerous technologies, such as J2EE and .NET.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories