Thursday, August 3, 2017

Internationalization - I18N in Struts

                                              Internationalization - I18N
                                               
If you use messages in your JSP pages, you can internationalize your application by having multiple properties files corresponding to the locale, as with standard I18N in Java.

It also help in centralized updates.
If a message is used in several places it can be updated with a single change.


1. Create a properties file in WEB-INF/classes
                         WEB-INF/classes/MessageResources.properties
            Define strings in the properties file in following format
            some.key1=first message
            some.key2=second message
            some.key3=some parameterized message: {0}

2. Configure properties file in struts-config.xml

3. Output the messages in jsp file.

1.    Creating MessageResources.properties file

email.title=Enter Your Email-Id
pass.title=Enter Your Password
submit.label=Login




2.    Configure properties file in struts-config.xml

            <message-resources parameter="MessageResources" null="false"/>
            "MessageResources" refers to WEB-INF/classes/MessageResources.properties,
            The null attribute determines whether missing messages should be flagged.
           If the value is true references to nonexistent messages result in null. That is a                  runtime exception.
           
 If the value is false, references to nonexistent messages result in warning messages                like ???keyName???.


3.    Output the messages in jsp file.

             <%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>
              <bean:message key="email.title"/>
              <bean:message key="pass.title"/>
                             
Redesigning registration.jsp using <bean:message>

<html>
<head>
<title>Html Form Demo</title>
</head>
<body>
            <%@ taglib uri="/WEB-INF/struts-html.tld"  prefix="html"%>
            <%@ taglib uri="/WEB-INF/struts-bean.tld"   prefix="bean"%>

            <html:form action="registerBean1" >
            <br>
                        <bean:message key="email.title"/>
                        <html:text property="email" /><br>

                        <bean:message key="pass.title"/>
                        <html:password property="password" /><br>
                       
                        <html:submit>
                                    <bean:message key=“submit.label"/>
                        </html:submit>

            </html:form>

</body>
</html>


                                                Implementing I18N
                                                           
            Create different MessageResouces for different locale.
For example for French create a MessageResouces_fr.properties file. Put all the entries values in French language.
If the locale of your browser changed to French, then automatically locale specific message will be fetched from MessageResouces_fr.properties file.
                                   
Using global forward:
    <global-forwards>
           <forward name="success"  path="/success.jsp"/>
    </global-forwards>
 Note :  this tag should be inserted after <form-beans> tag.

Error management in struts:

Struts have two main classes for error management:
1. ActionError – single error message (inherited from ActionMessage)
2. ActionErrors - act as a container for a collection of ActionError instances.(inherited from ActionMessages).


Creating ActionError Object
           
            ActionError provides multiple constructors:
            ActionError err = new ActionError(“errors.unknown”);
            ActionError err = new ActionError(“errors.unknown” , symbol);
            It assumes following entry is there in resource bundle:
            Errors.unknown = Unknown Symbol : {0}


Creating ActionErrors Object

ActionErrors errors= new ActionErrors();
errors.add(“property-name”, new ActionError(key));
<html:errors> tag

This tag is used to display  the ActionError objects stored in an ActionErrors collection.
It has two properties
                        1. errors.header
                        2. errors.footer
You can set these properties in property file. It will help to show errors in standard way.

Error handling in execute() of Action:
saveErrors(request,errors) ;
The result of this action is a request containing the errors collection being    forwarded to failure target that will display errors using <html:errors />

            1.  Add following error messages to MessageResources.properties file.
            email.incorrect=Email id : {0} is incorrect.
            password.incorrect=Incorrect Password 


2. Redesign UserBeanAction.java using saveErrors():
           
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

public class UserBeanAction extends Action {

       @Override
       public ActionForward execute(ActionMapping mapping,
                     ActionForm form,
                     HttpServletRequest request, HttpServletResponse response)
                     throws Exception {
              String res="invalid";
              UserBean userBean = (UserBean)form;
              String email=userBean.getEmail();
              String pass=userBean.getPassword();
             
              ActionMessages errors= new ActionMessages();
             
       if(email.equals("sonia@gmail.com"))
       {
                     if( pass.equals("sonia"))
                     {     
                           res="success";
                     }     
                            
                           errors.add("password",
                           new ActionMessage("password.incorrect"));
       }
       else
       {
              errors.add("email",
              new ActionMessage("email.incorrect",email));
       }
      
       saveErrors(request, errors);
       return mapping.findForward(res);
       }

}
      

       3. use <html:errors> tag in jsp file

<html>
<head>
<title>Html Form Demo</title>
</head>
<body>
       <%@ taglib uri="/WEB-INF/struts-html.tld"  prefix="html"%>
       <%@ taglib uri="/WEB-INF/struts-bean.tld"   prefix="bean"%>
      
       <div style="color:red"><html:errors/></div>    

       <html:form action="registerBean1" >
       <br>
              <bean:message key="email.title"/>
              <html:text property="email" /><br>

              <bean:message key="pass.title"/>
              <html:password property="password" /><br>
             
              <html:submit>
                     <bean:message key=“submit.label"/>
              </html:submit>

       </html:form>

</body>
</html>





Override the validate() of ActionForm:


import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import org.apache.struts.action.ActionForm;

public class UserBean  extends ActionForm{
      
private String email="";
private String password="";
public String getEmail() {
       return email;
}
public void setEmail(String email) {
       this.email = email;
}
public String getPassword() {
       return password;
}
public void setPassword(String password) {
       this.password = password;
       }



public ActionErrors validate(
              ActionMapping mapping,
              HttpServletRequest request) {
      
       ActionErrors errors= new ActionErrors();
      
       if(email.equals(""))
      
              errors.add("email", new ActionMessage("email.required"));
       if(password.equals(""))
              errors.add("password", new ActionMessage("password.required"));                  
      
      
       return errors;
}


}



Add properties related to validation in MessageResources.properties file
      
      
      email.required=Email cannot be blank.
       password.required=Password cannot be blank.


       #configure input form in struts-config.xml
      
       <action path="/registerBean2" type="mvc.UserBeanAction"
              name="userBean" scope="request" input="/registration1.jsp" validate="true">

                     <forward name="invalid" path="/invalid.jsp"/>
       </action>
               

                Use action="registerBean2"  in registration1.jsp file
               

<html>
<head>
<title>Html Form Demo</title>
</head>
<body>
       <%@ taglib uri="/WEB-INF/struts-html.tld"  prefix="html"%>
       <%@ taglib uri="/WEB-INF/struts-bean.tld"   prefix="bean"%>
      
       <div style="color:red"><html:errors/></div>    

       <html:form action="registerBean2" >
       <br>
              <bean:message key="email.title"/>
              <html:text property="email" /><br>

              <bean:message key="pass.title"/>
              <html:password property="password" /><br>
             
              <html:submit>
                     <bean:message key=“submit.label"/>
              </html:submit>

       </html:form>

</body>
</html>
You can also add <html:errors> tag in invalidate.jsp page



No comments:

Post a Comment