Struts internationalizing or localization example

This is a Struts localization example, displaying the message or content base on the specified selected language. By default, Struts will store a Locale attribute for each user in their session context under a key “org.apache.struts.action.LOCALE“, all you need to do is play around with this session attribute.

Download this Struts localization example – Struts-Localization-Example.zip

1. Project Structure

This is the project structure.

Struts-localization-folder

2. Properties file

All the localize messages are declared in properties file, format as “filename_locale_code.properties“. You can check the locale code in Java.Util.Locale class. e.g

  • English – Common.properties or Common_en_US.properties
  • Chinese – Common_zh_CN.properties
  • France – Common_fr.properties
  • German – Common_de.properties

Common.properties

#error message
error.common.username.required = Username is required
error.common.password.required = Password is required
 
#label message
label.common.message = localization example
label.common.username = Username 
label.common.password = Password
label.common.button.submit = Submit

Common_de.properties

#error message
error.common.username.required = Benutzername ist erforderlich
error.common.password.required = Passwort ist erforderlich
 
#label message
label.common.message = Lokalisierung Beispiel
label.common.username = Benutzername 
label.common.password = Kennwort
label.common.button.submit = Einreichen

3. Action class

Create a action class which extends DispatchAction for the multiple action purposes.

package com.mkyong.common.action;
 
import java.util.Locale;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.apache.struts.Globals;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
 
public class LanguageSelectAction extends DispatchAction{
 
	public ActionForward chinese(ActionMapping mapping,ActionForm form,
		HttpServletRequest request,HttpServletResponse response) 
	throws Exception {
 
		request.getSession().setAttribute(
				Globals.LOCALE_KEY, Locale.SIMPLIFIED_CHINESE);
 
		return mapping.findForward("success");
	}
 
	public ActionForward english(ActionMapping mapping,ActionForm form,
		HttpServletRequest request,HttpServletResponse response) 
	throws Exception {
 
		request.getSession().setAttribute(
				Globals.LOCALE_KEY, Locale.ENGLISH);
 
		return mapping.findForward("success");
	}
 
	public ActionForward german(ActionMapping mapping,ActionForm form,
		HttpServletRequest request,HttpServletResponse response) 
	throws Exception {
 
		request.getSession().setAttribute(
				Globals.LOCALE_KEY, Locale.GERMAN);
 
		return mapping.findForward("success");
	}
 
	public ActionForward france(ActionMapping mapping,ActionForm form,
		HttpServletRequest request,HttpServletResponse response) 
	throws Exception {
 
		request.getSession().setAttribute(
				Globals.LOCALE_KEY, Locale.FRANCE);
 
		return mapping.findForward("success");
	}
 
}

4. Action Form

Create a action form to hold the username and password data, and also for the form validation.

package com.mkyong.common.form;
 
import javax.servlet.http.HttpServletRequest;
 
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
 
public class UserForm extends ActionForm{
 
	String username;
	String password;
 
	public String getUsername() {
		return username;
	}
 
	public void setUsername(String username) {
		this.username = username;
	}
 
	public String getPassword() {
		return password;
	}
 
	public void setPassword(String password) {
		this.password = password;
	}
 
	@Override
	public ActionErrors validate(ActionMapping mapping,
		HttpServletRequest request) {
 
	    ActionErrors errors = new ActionErrors();
 
	    if( getUsername() == null || ("".equals(getUsername())))
	    {
	       errors.add("common.username.err",
	    	new ActionMessage("error.common.username.required"));
	    }
 
	    if( getPassword() == null || ("".equals(getPassword())))
	    {
	       errors.add("common.password.err",
	    	new ActionMessage("error.common.password.required"));
	    }
 
	    return errors;
	}
 
	@Override
	public void reset(ActionMapping mapping, HttpServletRequest request) {
		// reset properties
		username = "";
		password = "";
	}
}

5. JSP

Create a JSP page to display the language selection, form value and also the error message. The “/Locale.do?method=chinese” will match the DispatchAction chinese() method.

<%@taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
 
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1><bean:message key="label.common.message" /></h1>
 
<html:messages id="err_name" property="common.username.err">
<div style="color:red">
	<bean:write name="err_name" />
</div>
</html:messages>
 
<html:messages id="err_password" property="common.password.err">
<div style="color:red">
	<bean:write name="err_password" />
</div>
</html:messages>
<br />
<br />
<html:link page="/Locale.do?method=chinese">Chinese</html:link>
<html:link page="/Locale.do?method=english">English</html:link>
<html:link page="/Locale.do?method=german">German</html:link>
<html:link page="/Locale.do?method=france">France</html:link>
 
<html:form action="/Submit">
<br />
<bean:message key="label.common.username" /> : 
<html:text property="username" />
<br />
<br />
<bean:message key="label.common.password" /> : 
<html:text property="password" />
<br />
<br />
 
<html:submit>
   <bean:message key="label.common.button.submit" />
</html:submit>
</html:form>
 
</body>
</html>

6. struts-config.xml

Put it all together.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC 
"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" 
"http://jakarta.apache.org/struts/dtds/struts-config_1_3.dtd">
 
<struts-config>
 
	<form-beans>
		<form-bean
			name="userForm"
			type="com.mkyong.common.form.UserForm"/>
 
	</form-beans>
 
	<action-mappings>
 
		<action
			path="/LoginPage"
			type="org.apache.struts.actions.ForwardAction"
			parameter="/pages/multi-language.jsp"/>
 
		<action
			path="/Submit"
			type="com.mkyong.common.action.LanguageSelectAction"
			name="userForm"
			validate="true"
			input="/pages/multi-language.jsp"
			>
			<forward name="success" path="/pages/multi-language.jsp"/>
		</action>
 
		<action
			path="/Locale"
			type="com.mkyong.common.action.LanguageSelectAction"
			name="userForm"
			parameter="method"
			validate="false"
			>
			<forward name="success" path="/pages/multi-language.jsp"/>
		</action>
 
	</action-mappings>
 
	<message-resources
		parameter="com.mkyong.common.properties.Common" />
 
</struts-config>

7. wel.xml

Integrate the Struts framework in web deployment descriptor file.

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >
 
<web-app>
  <display-name>Maven Struts Examples</display-name>
 
  <servlet>
    <servlet-name>action</servlet-name>
    <servlet-class>
        org.apache.struts.action.ActionServlet
    </servlet-class>
    <init-param>
        <param-name>config</param-name>
        <param-value>
         /WEB-INF/struts-config.xml
        </param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
 
  <servlet-mapping>
       <servlet-name>action</servlet-name>
       <url-pattern>*.do</url-pattern>
  </servlet-mapping>
 
</web-app>

Screen shot

http://localhost:8080/StrutsExample/LoginPage.do

You can change the interface by the language links.

English interface

Struts-localization-english

Chinese interface

Struts-localization-chinese

France interface

Struts-localization-france

German interface

Struts-localization-german
Tags :

About the Author

mkyong
Founder of Mkyong.com and HostingCompass.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments