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

  • Pingback: ionizer payment plan()

  • Pingback: house blue()

  • Pingback: zak?ad szklarski piotrk√≥w trybunalski()

  • Pingback: continue reading()

  • Pingback: this site()

  • Pingback: pen style locksmith pick set()

  • Pingback: barry v locksmith()

  • Pingback: electricians lexington ky()

  • Pingback: electrician calculator()

  • Pingback: pay per day loans plan()

  • Pingback: alkaline water brands()

  • Pingback: water ionizer()

  • Pingback: laan penge nu uden renter()

  • Pingback: water ionizer()

  • Pingback: alkaline water()

  • Pingback: parking()

  • Pingback: lan penge her og lan penge nu()

  • Pingback: mobile porn()

  • Pingback: car parking()

  • Pingback: tvpackages.net()

  • Pingback: DIRECTV channels()

  • Pingback: get satellite tv()

  • Pingback: kangen water()

  • Pingback: kangen water()

  • Pingback: water ionizer()

  • Pingback: water ionizers()

  • Pingback: watch movies online free()

  • Pingback: watch tv show episodes()

  • Pingback: tv online, online tv()

  • Pingback: Blue Coaster33()

  • nagaraju

    Hi,
    the above example is absolutly fine
    but im unable to display exact chinese character in the browser.
    I also added the language fron interner >tool>language>chinese

    It will be a greate help if you can also explain how to implement this for korean language

  • raj

    when I am clicking on the submit button after giving username and password i am getting following error can any one help me how to resolve the issue as i am new to struts javax.servlet.ServletException: DispatchMapping[/Submit] does not define a handler property

  • http://newespressomachine.com/feed Espresso Machine

    Hi! I’ve been reading your web site for some time now and finally got the courage to go ahead and give you a shout out from New Caney Tx! Just wanted to say keep up the fantastic job!

  • kalyan

    The above example is not forwarding if i entered the required credentials like username and password also to the same page…..pls reply me

  • zion_ck

    Hi Mkyong,

    Greetings !!

    I read your blogs and it does great help in understanding and resolving issues i come across. Thank you for that.

    As i understand you are master of STRUTS. I have a weird situation and have put up the details at :
    http://stackoverflow.com/questions/15345824/global-exceptions-exception-key-does-not-pick-up-language-specific-value

    It would be great help if you could provide your insights.

    Thanks in advance,
    Kusuma

  • summ3r

    Hello,

    If you’re involved in software and website localization, I would warmly recommend a new translation tool that my team developed and will probably make your work easier: http://poeditor.com/

    POEditor is intuitive and collaborative. You can import from multiple localization file formats (like pot, po, xls, xlsx, strings, xml, resx) and, most importantly, we’re constanlty trying to enhance it based on our users’ feedback.

    Feel free to try it out and recommend it to developers and everyone who might find it useful.

    Thank you.

  • TestConfig

    Hello All,

    I was getting the following error.

    java.lang.VerifyError: (class: com/mkyong/common/action/LanguageSelectAction, method: signature: ()V) Constructor must call super() or this()

    To overcome this I declared constructor in LanguageSelectAction class, like this

    public LanguageSelectAction() {
    super();
    }
    It solved my problem.Hope it helps anyone.

  • Gail Ravenscroft

    Thank you for your great tutorials! Now I’m researching struts framework and your blog helps me a lot, you’re great!

  • Pingback: Struts 2 – i18n or localization example()

  • http://www.jitendraxxxx.blogspot.com Jitendra Singh Pal

    hi sir
    u r given good example
    now we want develop i189 website.but website having multiple page so how to change one page to another page
    just example google
    just one time click is possible and we get any language
    your example is only bse on one page. can you give me suggestion for multiple page
    thank u

  • Joseph Kingston Leo

    i tried here only chinese is not working for me but my browsers supports chinese.
    could you help in this case.

    • http://www.jitendraxxxx.blogspot.com Jitendra Singh Pal

      first of all u convert chines code to unicode then can get chines language

  • Joseph Kingston Leo

    I tried to add properties file with Japanese Language .I got translated username from google translate and tried to copy that into my properties file in eclipse i got error something like this ,
    some characters can’t be mapped due to ISO-8859-1.

    Please tell me how to get IS)-8859-1 encoded Japanese words.

    Thanks in Advance…………..

  • TigerKing

    Hi,

    If I want to implement a spanish, How could i set Locale?

  • pradeep

    your explanation on any topic is good. but i have one doubt on this internationalization. From where we have to get the .properties files for languages? or we have to write the .properties file ? why i am asking like this who has provide the .properties file for developers? or the developer has to create the .properties file for every language. Suppose i have to implement my application in 60 languages then what i should do? can i create 60 .properties files or can i get those .properties files from any where?

    Actually you have created one .properties file for German, in that only 2 fields are there. so that you have created the properties file easily. but in my application i have 100 fields then what i should do? and another one is we don’t know the languages of other countries then how should we create the .properties files.

  • Harini

    A good overview on localization . But would have been nice if you added more details on how the mapping happens between the setting the locale and why the particular property file was picked .

  • azhar

    Great tutorial.

  • Pingback: Struts Tutorials | J2EE Web Development Tutorials()