Tuesday, April 7, 2009

Use of ActionErrors in struts

  • Struts uses the ActionErrors instance returned by validate() to display the error messages on the redisplayed form.
  • ActionErrors (note the plural) is very much like a HashMap, and it is used to store error messages, indexed by error keys. The error message is not a String, but an instance of ActionMessage.
  • ActionMessages are added to an ActionErrors instance using the add() function:
  • public void add(String key, ActionMessage message)
  • eg. new ActionMessage("reg.error.password.mismatch")
  • For one thing, it’s obvious that we’re not passing in the actual error message! Instead, we’re passing in a key to an error message, stored in a properties file accessible to Struts.
  • Properties files are just text files, which contain key/value pairs. In this case, the key is reg.error.password.mismatch, and the value might be The passwords you keyed in don't match!.
  • # Properties file for Registration webapp
  • # Error messages: reg.error.userid.missing=The user id is missing.
  • reg.error.userid.exists = The user id exists. Choose another.
  • reg.error.userid.bad = Use only alphanumerics for the userid.
  • reg.error.password.mismatch = The passwords you keyed in don't match! reg.error.password.long = The password is too long!
  • reg.error.password.short = The password is too short!
  • The string argument of the ActionMessage constructor must be a key on a properties file.
  • This might seem restrictive, but there’s a very good reason for this. This is how Struts makes it easy to localize an application.
  • For example, if you wanted a German version of the Registration webapp, all you’d have to do would be hand over this properties file (registration.properties) for translation. You’d save the translated version as registration_de.properties, and bundle it with your webapp.
  • German users would see the German version of the Registration webapp and everyone else would see the default English version. Localizing a webapp was never so easy!

No comments:

Post a Comment

Followers