April 13, 2011

Struts 2 - Externalizing String literals using Resource Bundles

Modify the example code at the following link - http://www.javaissues.com/2011/04/struts-2-basic-validation-with-validate.html

1) In the Login.java class modify the validate() method as follows:

public void validate() {
   boolean flag = false;
   if (getUsername().length() == 0) {
      addFieldError("username", getText("username.required"));
      flag = true;
   if (getPassword().length() == 0) {
      addFieldError("password", getText("password.required"));
      flag = true;
   if (!flag) 
      if (!getUsername().equals("dinesh") && !getPassword().equals("dinesh")) {

2) Add 2 resource bundles (.properties files) in the same package as the Login.java class. The details of the files are below,


username.required=Username is required
password.required=Password is required
username.password.incorrect=Username and/or Password is Incorrect


username.required=Username is required in Hindi
password.required=Password is required in Hindi
username.password.incorrect=Username and/or Password is Incorrect in Hindi

3) Test the code by typing the following URL in the browser


Now, change the language setting in the browser to Hindi [hi] and type the above URL again in the browser.

No comments:

Post a Comment