Apache Wicket Internationalization Locale and ResourceBundle Example explained step by step below.

As usual in Java i18n systems, messages are looked up by locale. The locale is automatically extracted from the HTTP request, but can also be explicitly set with getSession().setLocale(Locale.US).

Prerequisite: Eclipse & JDK setup

If you don’t have Eclipse and JDK installed, follow this URL –

https://digitalappconsultancy.com/site/learning-java-hello-world-example/

Software used are listed below;

Eclipse 4.6.x
JDK 1.8.x
Apache Wicket 7.7.x
Apache Tomcat 8.5
Maven & Wicket (optional) Eclipse Plugin

Finally the project should look as below;

Step 1: Basic sofware setup;

If you already have them Jump to Step 2

1. Maven & Apache Wicket Plugin Install
2. Tomcat 8.5 server installation and setup

Refer – https://digitalappconsultancy.com/site/eclipse-tomcat-apache-wicket-maven-setup-with-hello-world-example/

Step 2: New Maven project

Create new Maven project -> Create Simple project (skip archetype selection) – Provide details as below;

Step 3: Update pom.xml & web.xml

Your web.xml should look as below;

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>MyWebApp</display-name>
  
   <filter>
        <filter-name>MyWebAppApplication</filter-name>
        <filter-class>org.apache.wicket.protocol.http.WicketFilter</filter-class>
        <init-param>
          <param-name>applicationClassName</param-name>
          <param-value>com.webapp.WicketApplication</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>MyWebAppApplication</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

 

Update Maven pom.xml to download tomcat plugin and Apache wicket framework and Junit framework.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>MyWebApp</groupId>
    <artifactId>MyWebApp</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <build>
        <sourceDirectory>src/main/java</sourceDirectory>
        <testSourceDirectory>src/test/java</testSourceDirectory>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.0.0</version>
                <configuration>
                    <warSourceDirectory>WebContent</warSourceDirectory>
                </configuration>
            </plugin>

            <!-- Tomcat Maven plugin to deploy war file -->
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.2</version>
                <configuration>
                    <url>http://localhost:8080/manager/text</url>
                    <server>TomcatServer</server>
                    <path>/MyWebApp</path>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <!-- Apache Wicket Jars -->
        <dependency>
            <groupId>org.apache.wicket</groupId>
            <artifactId>wicket-core</artifactId>
            <version>7.7.0</version>
        </dependency>
        
        <!-- https://mvnrepository.com/artifact/junit/junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        
        <!-- Apache Wicket Testing need this jar -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.0.1</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
</project>

 

Step 5: Create Wicket HomePage with form Model

1. Create DropDown.java which is model object for drop down objects.
2. Create HomePage.java which is home page as application URL invoked.
3. Create HomePage.html which is view page as application URL invoked.
4. Create HomeForm.java which is model form for the Home Page.

Complete WicketApplication.java provided below

package com.webapp;

import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.protocol.http.WebApplication;

import com.webapp.page.HomePage;

public class WicketApplication extends WebApplication
{
    @Override
    public Class<? extends WebPage> getHomePage()
    {
            return HomePage.class;
    }

    @Override
    public void init()
    {
            super.init();
            // add your configuration here           
    }
}

Complete DropDown.java provided below

/**
 * 
 */
package com.webapp.page;

public class DropDown {
    String code;
    String displayValue;
    
    /**
     * @param code
     * @param displayValue
     */
    public DropDown(String code, String displayValue) {
        super();
        this.code = code;
        this.displayValue = displayValue;
    }
    
    
    /**
     * @return the code
     */
    public String getCode() {
        return code;
    }
    /**
     * @param code the code to set
     */
    public void setCode(String code) {
        this.code = code;
    }
    /**
     * @return the displayValue
     */
    public String getDisplayValue() {
        return displayValue;
    }
    /**
     * @param displayValue the displayValue to set
     */
    public void setDisplayValue(String displayValue) {
        this.displayValue = displayValue;
    }
}

Complete HomePage.java provided below

/**
 * 
 */
package com.webapp.page;

import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.request.mapper.parameter.PageParameters;

/**
 * @author Niranjan Velagapudi
 *
 */
public class HomePage extends WebPage{

    /**
     * 
     */
    private static final long serialVersionUID = 5946349607750478191L;
    

    public HomePage(final PageParameters parameters) {
        super(parameters);
    	add(new HomeForm("homeForm"));
    }
}

Complete HomeForm.java provided below

/**
 * 
 */
package com.webapp.page;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;

import org.apache.wicket.Session;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.IChoiceRenderer;
import org.apache.wicket.model.AbstractReadOnlyModel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.IModel;

public class HomeForm extends Form {

    private static final long serialVersionUID = 157873863293813131L;
    
    private Label messageLabel;
    private DropDown languageChoice;
    private AbstractReadOnlyModel<String> model; 

    public HomeForm(String id) {		
        super(id);
        setDefaultModel(new CompoundPropertyModel(this));
        
        // Create DropDown choices for Language Locale
        DropDown english = new DropDown("en-US", "English");
        DropDown french = new DropDown("fr-FR", "French");    
        DropDown telugu = new DropDown("te-IN", "Telugu");  
        DropDown tamil = new DropDown("ta-IN", "Tamil");  
        List<DropDown> languageList = new ArrayList<DropDown>(4);
        languageList.add(english);
        languageList.add(french);
        languageList.add(telugu);
        languageList.add(tamil);
        // Set the default value
        languageChoice = english;
        		
        final DropDownChoice<DropDown> localeDropDownChoice = new DropDownChoice<DropDown>("languageChoice", languageList, new IChoiceRenderer<DropDown>() {    
            private static final long serialVersionUID = -4646085568193331620L;
            @Override
            public Object getDisplayValue(DropDown object) {                
                return object.getDisplayValue();
            }
        
            @Override
            public String getIdValue(DropDown object, int index) {
                return object.getCode();
            }
        
            @Override
            public DropDown getObject(String id, IModel choices) {
                Iterator<DropDown> itr = languageList.iterator();
                while(itr.hasNext()){
                    DropDown choice = itr.next();
                    if(choice.getCode().equals(id)){
                        return choice;
                    }
                }
                return null;
            }           
        });
        localeDropDownChoice.setOutputMarkupId(true);
        localeDropDownChoice.setNullValid(false);
        add(localeDropDownChoice);
        
        // Create Ajax Handler to handle the change in Language choice
        localeDropDownChoice.add(new AjaxFormComponentUpdatingBehavior("onchange") {			
            @Override
            protected void onUpdate(AjaxRequestTarget target) {
                
                // Extract the locale and setup that for the session
                String[] localeSplit = languageChoice.getCode().split("-");
                Session.get().setLocale(new Locale(localeSplit[0], localeSplit[1]));
                messageLabel.setDefaultModelObject(model.getObject());
                
                
                target.add(messageLabel);
            }
        });
        
        // Default the English
        Session.get().setLocale(new Locale("en", "US"));
                 
        model = new AbstractReadOnlyModel<String>() {
            @Override
            public String getObject() {
                return getString("message");
            }
        };

        messageLabel = new Label("message",model);
        messageLabel.setOutputMarkupId(true);
        add(messageLabel);
    }
}

Complete HomePage.html provided below

<?xml version="1.0" encoding="UTF-8"?>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:wicket="http://wicket.apache.org">
<head>
    <title>Wicket Login Form Model</title>
    <link rel="stylesheet" type="text/css" href="style.css"/>
</head>
<body>
     <form id="homeForm" method="post" wicket:id="homeForm">
 	  <table>
 	  	<tr>
 	  		<td>
 	  			<select wicket:id="languageChoice" id="languageChoice" name="languageChoice"/><BR>
 	  		</td>
 	  		<td>&nbsp;</td>
 	  		<td>
 	  		 	<font color="blue"><p wicket:id="message" /></font>
 	  		</td>
 	  	</tr>
 	  </table>
 	 </form> 
</body>
</html>

 
Complete HomePage_en.properties.xml provided below

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
    <entry key="message">Happy New Year!</entry>
</properties>

 
Complete HomePage_fr.properties.xml provided below

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
    <entry key="message">Bonne année</entry>
</propertie

Complete HomePage_te.properties.xml provided below

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
    <entry key="message">నూతన సంవత్సర శుభాకాంక్షలు</entry>
</properties>

Complete HomePage_ta.properties.xml provided below

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
    <entry key="message">புத்தாண்டு வாழ்த்துக்கள்</entry>
</properties>

 

Step 6: Unit testing with JUnit Framework
Important feature comes with Apache Wicket framework is ability to unit test Markup (html view) via JUnits.

Create TestHomePage class under src/test/java package as below;

/**
 * 
 */
package com.test.page;

import org.apache.wicket.util.tester.FormTester;
import org.apache.wicket.util.tester.WicketTester;
import org.junit.Before;
import org.junit.Test;

import com.webapp.WicketApplication;
import com.webapp.page.HomePage;

/**
 * @author Niranjan Velagapudi
 *
 */
public class TestHomePage {
    private WicketTester tester;

    @Before
    public void setUp() {
        tester = new WicketTester(new WicketApplication());
    }

    @Test
    public void loginpageRendersSuccessfully() {
        // start and render the test page
        tester.startPage(HomePage.class);
        // assert rendered page class
        tester.assertRenderedPage(HomePage.class);
        
        // Change drop down to French and do Ajax call.
        FormTester formTester = tester.newFormTester("homeForm");
        formTester.select("languageChoice", 1);  // Selecting French in the drop down
        tester.executeAjaxEvent("homeForm:languageChoice", "onchange"); 
        
        tester.assertNoErrorMessage(); 
        tester.assertRenderedPage(HomePage.class); 
        tester.assertModelValue("homeForm:message", "Bonne année");
    }
    
}

 

Finally the project should look as below;

Right click on pom.xml and Run As – Maven with specific goal “tomcat7:deploy” for first time and to redeploy “tomcat7:redeploy”

If Deployment is successful, you should be able to view the Home Page as below;

Access url – http://localhost:8080/MyWebApp

 

Change the Language drop down to French and you will notice label changed in French.

For further reading refer Apache Wicket Web Development Category posts.

Apache Wicket Internationalization Locale and ResourceBundle Example
Tagged on:     

Leave a Reply

Your email address will not be published. Required fields are marked *