Struts LocaleAction

The SwitchAction class allows you to configure multiple application modules. SwitchAction (org.apache.struts.actions.SwitchAction) is a standard Action that can switch to another module and then forward control to a path within that module.

SwitchAction expects two request parameters to be passed:

  • Implement dynamic forms, one of each locale you want to allow users to switch to. These forms must contain a language property representing the locale’s langauge code. You must set the initial value of this property to the locale’s language code (e.g. Es for Spanish). You may optional specify a country attribute for the locale’s country code. Again, the intial values of the country property must be set to the country code. The page to forward to after setting the locale is specified with the page request parameter.
  • Put in a form handler ( tag) for each of these dyanmic forms. The single tag should be named success and must point to the page you want display in the new language.

1. Create DynaActionForm

First we create an entry for DynaActionForm for each locale in struts-config.xml

  <form-bean name="English" type="org.apache.struts.action.DynaActionForm">  
      <form-property name="language" type="java.lang.String" initial="en" />  
      <form-property name="country" type="java.lang.String" initial="US" /> 
      <form-property name="page" type="java.lang.String" initial="/locale.jsp" />   
  <form-bean name="Spanish" type="org.apache.struts.action.DynaActionForm">  
      <form-property name="language" type="java.lang.String" initial="es" />  
      <<form-property name="country" type="java.lang.String" initial="ES">  
      <form-property name="page" type="java.lang.String" initial="/locale.jsp" />  

2. Create ActionMapping

Next we create an action mapping for this action handler.

<action path="/toEnglish" name="English" 
  <forward name="success" path="/locale.jsp" />  
<action path="/toSpanish" name="Spanish" 
  <forward name="success" path="/locale.jsp" />  

3. Create JSP Page

Now create the jsp page that delegates requests to different jsp pages.

To allow users to switch locales, you’d have to put in s to the relevant form handlers.

<<%@ taglib uri="" prefix="html"%>
<%@ taglib uri="" prefix="bean"%>
<title>Struts LocaleAction</title>
<html:link action="/toEnglish"><bean:message key="label.english"/></html:link>
<html:link action="/toSpanish"><bean:message key="label.spanish"/></html:link>

4. Run Project

Now when you run the project, following screen will be displayed as shown in Figure 11.1

Figure 11.1 Figure 11.1

Now when you click on Spanish link, following screen will be displayed as shown in Figure 11.2

Figure 11.2 Figure 11.2

The folder structure of the example is shown below in Figure 11.3

Figure 11.3 Figure 11.3

You can download the source code of this example here.

No comments yet.

Leave a Reply