Featured Post

Event Sourcing Video from Michael Ploed

Event Sourcing I want to share a great video I found few days ago that describes very well what Event Sourcing is.

Saturday, May 5, 2012

Struts Internationalization

In this post we see how internationalization works in the framework Struts 1.X.

Step 1: Create a Struts Action

We have to create a Java Class that extends an action of Struts framework. The Action in the following code has the only function to forward the requests to a JSP called simpleForward.

package com.simonefolinojavablog.struts_internationalization.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.MappingDispatchAction;

public class InternationalizationAction extends MappingDispatchAction{

 public ActionForward simpleForward(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response) throws Exception {
  return mapping.findForward("simpleForward");

Step 2: Declare inside struts-config.xml the presence of internationalization files

In the configuration file struts-config.xml we have to put the location of the files containing labels for the internationalization.

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



  <action path="/internationalization" 
   <forward name="simpleForward" 
            path="/jsp/simpleForward.jsp" />


        <!--ApplicationResources is the name of the file containing labels -->
 <message-resources parameter="ApplicationResources" />


Step 3: Create files with extension .properties containing labels

You have to create a file for each language you want to provide for your web application. Each file must contain the same set of label keys and the values of these keys have to differ in the language used.




Step 4: Create JSP that use labels

We have declared for the Action, a View to use (simpleForward.jsp). Now we have to create it.

<%@ page language="java"%>
<%@ taglib prefix="bean" uri="http://struts.apache.org/tags-bean"%>


 <bean:message key="welcome.label" />



If we connect to the web application, when the InternationalizationAction is called, it forwards us to the JSP simpleForward.jsp. This page has been internationalized, so if you use an italian client agent you can see Benvenuto! otherwise if you use an English client agent you can see Welcome!.

No comments :

Post a Comment