Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction🤔
2.
Struts2 Localization, Internationalization (i18n)🎯
3.
Resource Bundles💻
4.
Access the messages👨🏻‍💻
4.1.
getText🎯
4.2.
The text Tag🤔
4.3.
The i18n Tag🎯
4.4.
The key Attribute👨🏻‍💻
5.
Localization Example🤔
5.1.
Action to take care of Locale🎯
5.2.
Action To Submit The Form🖥️
5.3.
global.properties👨🏻‍💻
5.4.
global_fr.properties🤔
5.5.
global_es.properties👨🏻‍💻
5.6.
Output💻
6.
Frequently Asked Questions
6.1.
Define internationalization.
6.2.
What are the Struts 2 core components?
6.3.
What is the distinction between Struts 1 and Struts 2?
6.4.
What are the various methods for gaining access to message resources?
6.5.
What is Struts XML?
7.
Conclusion
Last Updated: Mar 27, 2024
Medium

Struts2 Localization, Internationalization (i18n)

Introduction🤔

Apache Struts 2 is a sophisticated, flexible framework for developing enterprise-class Java web applications. This framework is intended to simplify the whole development cycle, from application creation through deployment and maintenance over time.

struts2 coding ninjas

This blog will go through Struts2 Localization, internationalization (i18n) in detail with examples.

Struts2 Localization, Internationalization (i18n)🎯

Internationalization (i18n) is the design and implementation of products and services so that they may be readily modified to specific local languages and cultures, a process known as localization. The process of internationalisation is known as translation or localization enablement.

Internationalization is abbreviated i18n because the term begins with the letter “I” and ends with "n". There are 18 characters between the initial I and the final n.

Struts2 supports localization, also known as internationalisation (i18n), in the following places through resource bundles, interceptors, and tag libraries.

  • The UI Tags
  • Messages and Errors.
  • Within action classes.

Resource Bundles💻

Resource bundles are files that contain the key/value pairs for your application's default language. Struts2 takes advantage of resource bundles to give web application users numerous language and locale options. You don't have to bother about creating pages in many languages. All you need to do is build a resource bundle for each language you wish to use. The resource bundles will include titles, messages, and other content in your user's language.

The most essential resource file name format is:

bundlename_language_country.properties


bundlename in the above code might be actionclass, interface, superclass, model, package, or global resource attributes. The next element, language_country, represents the country locale. e.g., spanish (Spain) locale is represented by es_ES, english (United States) location is represented by en_US, and so on.

When you refer to a message element by its key, the Struts framework looks for a corresponding message bundle in the sequence listed below.

  • ActionClass.properties
  • Interface.properties
  • SuperClass.properties
  • model.properties
  • package.properties
  • struts.properties
  • global.properties
     

To design your application in different languages, you must keep several property files for each language/locale and define all information as key/value pairs.

For example, you'll need three properties files if you want to construct your app for US english (default), spanish, and french. Here we will be using the global.properties file.

  • global.properties: English (United States) will be used by default.
  • global_fr.properties: This is for the french locale.
  • global_es.properties: This will be used for the spanish locale.

Access the messages👨🏻‍💻

There are various methods for accessing message resources, including getText, the text tag, the key attribute of UI tags, and the i18n tag. Let us look at them briefly.

getText🎯

To show i18n text, use a getText call in the property tag or any other tag, such as the UI tags listed below.

<s:property value = "getText('some.key')" />

The text Tag🤔

The text tag pulls a message from the default resource bundle, struts.properties.

<s:text name = "some.key" />

The i18n Tag🎯

The i18n tag adds any resource bundle to the value stack. Other tags inside the i18n tag's scope can display messages from that resource bundle.

<s:i18n name = "some.package.bundle">
   <s:text name = "some.key" />
</s:i18n>

The key Attribute👨🏻‍💻

The key attribute of most UI tags may be utilised to produce a message from a resource bundle.

<s:textfield key = "some.key" name = "textfieldName"/>

Localization Example🤔

First, create the index.jsp file and write the following code in it.

<%@ page language = "java" contentType = "text/html; charset = ISO-8859-1"
   pageEncoding = "ISO-8859-1"%>
<%@ taglib prefix = "s" uri = "/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">

<html>
   <head>
      <title>Student Form with Multilingual Support</title>
   </head>

   <body>
      <h1><s:text name = "global.heading"/></h1>

      <s:url id = "indexEN" namespace="/" action = "locale" >
         <s:param name = "request_locale" >en</s:param>
      </s:url>
      
      <s:url id = "indexES" namespace="/" action = "locale" >
         <s:param name = "request_locale" >es</s:param>
      </s:url>
      
      <s:url id = "indexFR" namespace="/" action = "locale" >
         <s:param name = "request_locale" >fr</s:param>
      </s:url>

      <s:a href="%{indexEN}" >English</s:a>
      <s:a href="%{indexES}" >Spanish</s:a>
      <s:a href="%{indexFR}" >France</s:a>

      <s:form action = "studid" method = "post" namespace = "/">
         <s:textfield name = "name" key = "global.name" size = "20" />
         <s:textfield name = "age" key = "global.age" size = "20" />
         <s:submit name = "submit" key = "global.submit" />
      </s:form>

   </body>
</html>


The next step is to create a success.jsp file, which will be invoked if the specified operation returns SUCCESS.

<%@ page language = "java" contentType = "text/html; charset = ISO-8859-1"
pageEncoding = "ISO-8859-1"%>
<%@ taglib prefix = "s" uri = "/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
   "http://www.w3.org/TR/html4/loose.dtd">

<html>
   <head>
      <title>Success</title>
   </head>
   
   <body>
      <s:property value = "getText('global.success')" />
   </body>
</html>


In this case, we would need to construct the two actions shown below.

  1. The first step is to take care of the locale and show the same index.jsp file in multiple languages.
     
  2. Another action is to handle the form submission itself.
     

Both actions will return SUCCESS, but we will take different actions based on the return values because the purposes of the actions are other.

Action to take care of Locale🎯

Below is the code for the action to take care of the locale.

package com.codingninjas.struts2;


import com.opensymphony.xwork2.ActionSupport;


public class Locale extends ActionSupport {
   public String execute() {
       return SUCCESS;
   }
}

Action To Submit The Form🖥️

Following is the java code for the action to submit the form.

package com.codingninjas.struts2;

import com.opensymphony.xwork2.ActionSupport;

public class Student extends ActionSupport{
   private String name;
   private int age;
   
   // Functio to check success
   
   public String execute() {
      return SUCCESS;
   }
   
   // Getter Function for name
   
   public String getName() {
      return name;
   }
   
   // Setter function for name
   
   public void setName(String name) {
      this.name = name;
   }
   
   // Getter function for age
   
   public int getAge() {
      return age;
   }
   
   // Setter function for age
   
   public void setAge(int Ag) {
      this.age = Ag;
   }
}


Let us now create three global.properties files and add them to the CLASSPATH.

global.properties👨🏻‍💻

Below is the code for the global.properties file:

global.name = Name
global.age = Age
global.submit = Submit
global.heading = Select Locale
global.success = Successfully authenticated

global_fr.properties🤔

Below is the code for the global_fr.properties file:

global.name = Nom d'utilisateur 
global.age = l'âge
global.submit = Soumettre des
global.heading = Sélectionnez les paramètres régionaux
global.success = Authentifié avec succès

global_es.properties👨🏻‍💻

Below is the code for the global_es.properties file:

global.name = Nombre de usuario
global.age = Edad
global.submit = Presentar
global.heading = seleccionar la configuracion regional
global.success = Autenticado correctamente


We will construct struts.xml with the following two actions:

<?xml version = "1.0" Encoding = "UTF-8"?>
<!DOCTYPE struts PUBLIC
   "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
   "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
   <constant name = "struts.devMode" value = "true" />
   <constant name = "struts.custom.i18n.resources" value = "global" />
   <package name = "helloworld" extends = "struts-default" namespace="/">
      <action name = "empinfo" 
         class = "com.codingninjas.struts2.Employee"
         method = "execute">
         <result name = "input">/index.jsp</result>
         <result name = "success">/success.jsp</result>
      </action>
      
      <action name = "locale" 
         class = "com.codingninjas.struts2.Locale"
         method = "execute">
         <result name = "success">/index.jsp</result>
      </action>
   </package>

</struts>


The following is the web.xml file's content.

<?xml version = "1.0" Encoding = "UTF-8"?>
<web-app xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xmlns = "http://java.sun.com/xml/ns/javaee"
   xmlns:web = "http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
   xsi:schemaLocation = "http://java.sun.com/xml/ns/javaee
   http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
   id = "WebApp_ID" version = "3.0">

   <display-name>Struts 2</display-name>
   <welcome-file-list>
      <welcome-file>index.jsp</welcome-file>
   </welcome-file-list>

   <filter>
      <filter-name>struts2</filter-name>
      <filter-class>
         org.apache.struts2.dispatcher.FilterDispatcher
      </filter-class>
   </filter>

   <filter-mapping>
      <filter-name>struts2</filter-name>
      <url-pattern>/*</url-pattern>
   </filter-mapping>
</web-app>

Output💻

To produce a War file, right-click on the project name and select Export > WAR File. After that, place this WAR in Tomcat's webapps directory. Finally, launch Tomcat and navigate to http://localhost:8080/HelloWorldStruts2/index.jsp.

The above procedure will provide the following screen.

output struts2 localization

Choose any language, such as french, and the following result will be displayed.

output struts2 internationalization

You may also try the Spanish language. Finally, if we click the submit button while in the France locale, we will get the screen below.

output struts localization

Congratulations, you now have a multilingual website that can be launched internationally.

Frequently Asked Questions

Define internationalization.

Internationalization is designing and implementing products and services so that they may be readily modified to specific local languages and cultures, a process known as localization. 

What are the Struts 2 core components?

The three major struts2 building components are the action, interceptor, and result pages. Struts2 allows you to define and customise action classes in various ways.

What is the distinction between Struts 1 and Struts 2?

Struts 1 supports separate request processors (lifecycles) for each module, but all modules must utilise the same lifecycle. Struts 2 allows the construction of several lifecycles for each action using interceptor stacks. Custom stacks can be built and applied to numerous actions as needed.

What are the various methods for gaining access to message resources?

The message resources may be accessed using numerous methods, including getText, the text tag, and the i18n tag.

What is Struts XML?

The struts.xml file contains the configuration data that will be changed when actions are generated. DevMode = false, as well as other default parameters provided in property files, can be altered for an application that uses this file, such as struts.

Conclusion

In this article, we have extensively discussed struts2 localization, internationalization. 

Do you not feel eager to read/explore additional information on the subject of Struts 2 after reading about struts2 localization, internationalization? See the Struts 2 documentationStruts Tutorial for beginnersStruts 2 Intro, and 15 Best Java frameworks to use in 2022-Coding Ninjas.

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enrol in our courses and refer to the mock test and problems available. Take a look at the interview experiences and interview bundle for placement preparations.

Do upvote our blog to help other ninjas grow. 

Happy Learning Ninja! 🥷

thank you image
Live masterclass