The topic template and internationalization settings in the Struts framework of Java,

Source: Internet
Author: User

The topic template and internationalization settings in the Struts framework of Java,

Topic Template

If no subject is specified, the default XHTML topic is used in Struts2. For example, select a tag in Struts 2:

<s:textfield name="name" label="Name" />

Generate HTML Tag:

<tr><td class="tdLabel">  <label for="empinfo_name" class="label">Name:</label></td><td>  <input type="text" name="name" value="" id="empinfo_name"/></td></tr>

The action name is defined in the empinfo struts. xml file.

Select a topic:
You can specify the topic Struts 2 based on each tag or the specified topic Struts 2. You can use either of the following methods:

  • Tags of topic attributes
  • Form tag of the topic property tag
  • The property of the page range, named "topic"
  • The request range attribute is named "topic"
  • The session scope attribute is named "topic"
  • The attribute of the application scope is named "topic"

In struts. properties struts. ui. theme attributes (XHTML by default)

The following syntax specifies them at the tag level. If you want to use different topics for different tags:

<s:textfield name="name" label="Name" theme="xhtml"/>

Because it is not very practical, the topic is used on the basis of each tag, we can simply specify the following tag in the Rule struts. properties file:

# Standard UI themestruts.ui.theme=xhtml# Directory where theme template residesstruts.ui.templateDir=template# Sets the default template type. Either ftl, vm, or jspstruts.ui.templateSuffix=ftl

The result below is that we pick up from the localization chapter we use the default settings in the struts. ui. theme = XHTML struts-default.properties file, by default, In the struts2-core.xy.z.jar file, which is made by the subject.

How do theme work?
For a given topic, each struts tag has an associated template, such as s: textfield-> text. ftl and s: password-> password. ftl, etc. These template files are used to compress struts2-core.xy.z.jar files. These template files maintain a predefined HTML layout for each tag. Therefore, the Struts2 framework generates the final HTML Tag code using the Sturts tag and related templates.

Struts 2 tags + Associated template file = Final HTML markup code.

The default template has been written in FreeMarker and they have the extension. ftl. You can design or use a velocity or JSP template, and configure it accordingly when using struts. ui. templateSuffix and struts. ui. templateDir struts. properties.

Create a new topic:
The simplest way to create a new topic is to copy any existing topic/template file and make necessary modifications. So, let's start creating a folder WebContent/WEB-INF/classes named template and subfolders with the name of our new theme, such as WebContent/WEB-INF/classes/template/mytheme. From here, you can build a template from the beginning, or copy the template from the Struts2 distribution and modify it as needed.

We need to modify the existing default template XHTML for learning purpose. So now let's copy the content from struts2-core-x.y.z.jar/template/xhtml to our theme directory and just modify the WebContent/WEB-INF/classes/template/mytheme/control. ftl file. When we open control. ftl, it will have the following lines:

<table class="${parameters.cssClass?default('wwFormTable')?html}"<#rt/><#if parameters.cssStyle??> style="${parameters.cssStyle?html}"<#rt/></#if>>

Let's change the control. ftl file to the following:

<table style="border:1px solid black;">

If you check form. ftl, you will find that the form. ftl file in the control. ftl file refers to the XHTML subject. Therefore, let's change it as follows:

<#include "/${parameters.templateDir}/xhtml/form-validate.ftl" /><#include "/${parameters.templateDir}/simple/form-common.ftl" /><#if (parameters.validate?default(false))> onreset="${parameters.onreset?default('clearErrorMessages(this); clearErrorLabels(this);')}"<#else> <#if parameters.onreset??> onreset="${parameters.onreset?html}" </#if></#if>><#include "/${parameters.templateDir}/mytheme/control.ftl" /> 

I suppose I don't know much about the FreeMarker template language, but I still find out what the FTL file needs to do. I can get a good idea. However, let's go back to our localization example in addition to the above changes and create the following content for the WebContent/WEB-INF/classes/struts. properties file:

# Customized themstruts.ui.theme=mytheme# Directory where theme template residesstruts.ui.templateDir=template# Sets the template type to ftl.struts.ui.templateSuffix=ftl

Now, right-click the project name and choose Export> WAR File to create a WAR File. Then deploy the WAR in the webapps directory of Tomcat. Finally, start the Tomcat server and try to access URL http: // localhost: 8080/HelloWorldStruts2. The following figure is displayed:

After copying the XHTML topic, we made the topic. This is a result and we can see the border around a form component. FreeMarker is easy to create or modify themes if you work hard. At least now, you must have a basic understanding of Sturts2 themes and templates.

Localization/Internationalization
I18n is a planning and implementation product and service that enables them to easily adapt to specific local languages and cultures. This process is called localization. The process of internationalization is sometimes referred to as enabling translation or localization. I18n is short for internationalization, Because I and the two ends use n to start with, and there are 18 characters between I and the last n.

Struts2 provides localization, that is, International (i18n) Support, through the resource package, interceptor and tag library in the following places:

  • UI tag
  • Messages and errors
  • Category

Resource Package:
Struts2 uses a resource package to provide multi-language and regional options for Web applications. Don't worry about writing web pages in different languages. All that must be done is to create a resource package for each desired language. The resource package contains the title, message, and other text language users. Resource Package file, which contains the default language of the key/value pair for your application.

Resource files in simple naming formats are:

Bundlename_language_country.properties
Here, the software package can be ActionClass, interface, superclass, model, encapsulation, and global resource attributes. The following sections refer to age_country and En_US. You can skip this section to indicate es_ES and English (USA). Spanish (Spain) indicates the language environment, for example, it represents a country.

When a message element is referenced, the key is to search the Struts Framework of the corresponding message package in the following order:

  • ActionClass. properties
  • Interface. properties
  • SuperClass. properties
  • Model. properties
  • Package. properties
  • Struts. properties
  • Global. properties

To develop applications in multiple languages, you must maintain all the content in the key/value pairs defined by multiple attribute files in those languages/regions. For example, if you want to develop an application (default) that is in American English, Spanish, or French, you must create three Property Files. Here, I will use only the global. properties file. You can use different attribute files to isolate different types of messages.

  • Global. properties: by default, English (USA) will be applied.
  • Global_fr.properties: this will be used in a French environment.
  • Global_es.properties: this will be used in the Spanish language environment.

Access message:
There are several methods to access information resources, including gettext, text tags, key attributes of UI tags, and International tags. Let's take a look at their simplicity:

To display the i18n text, use the call property tag gettext or any other tag. For example, the UI tag is as follows:

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

Text tag retrieval from the default resource package, that is, a message struts. properties

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

Any resource bundle on the i18n tag push stack. Other labels in the i18n label range can display messages of the resource package:

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

Key attributes of most UI tags can be used to retrieve messages from a resource package:

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

Localization example:
The created index. jsp is from the previous chapter to multiple languages. The same file will be written as follows:

<%@ 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">

We will create the success. jsp file, which will return the SUCCESS action defined when it is called.

<%@ 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">

Here, we need to create two actions. (1) The first action is Locale and care, and the same index. jsp file is displayed in different languages (2) another action is to take care of the submission form itself. All actions will return SUCCESS, but we will take different actions based on the returned values, because our purpose is to have two different actions:

Action processing locale:

package com.yiibai.struts2;import com.opensymphony.xwork2.ActionSupport;public class Locale extends ActionSupport{  public String execute()   {    return SUCCESS;  }}

Action for submitting a form:

package com.yiibai.struts2;import com.opensymphony.xwork2.ActionSupport;public class Employee extends ActionSupport{  private String name;  private int age;    public String execute()   {    return SUCCESS;  }    public String getName() {    return name;  }  public void setName(String name) {    this.name = name;  }  public int getAge() {    return age;  }  public void setAge(int age) {    this.age = age;  }}

Now. Let's create the following three global. properties files in CLASSPATH:

GLOBAL.PROPERTIES:global.name = Nameglobal.age = Ageglobal.submit = Submitglobal.heading = Select Localeglobal.success = Successfully authenticatedGLOBAL_FR.PROPERTIES:global.name = Nom d'utilisateur global.age = l'âgeglobal.submit = Soumettre desglobal.heading = Sé lectionnez Localglobal.success = Authentifi é avec succèsGLOBAL_ES.PROPERTIES:global.name = Nombre de usuarioglobal.age = Edadglobal.submit = Presentarglobal.heading = seleccionar la configuracion regionalglobal.success = Autenticado correctamente

We will create two actions in struts. xml as follows:

<?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.yiibai.struts2.Employee"     method="execute">     <result name="input">/index.jsp</result>     <result name="success">/success.jsp</result>   </action>      <action name="locale"      class="com.yiibai.struts2.Locale"     method="execute">     <result name="success">/index.jsp</result>   </action>  </package></struts>

The content in the web. xml file is as follows:

<?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>

Right-click the project name and choose Export> WAR File to create a WAR File. Then deploy the WAR in the webapps directory of Tomcat. Finally, start the Tomcat server and try to access the URL http: // localhost: 8080/HelloWorldStruts2/index. jsp. The following figure is displayed:

Now select any language, let's speak, we select Spanish, this will show the following results:

You can try french. Finally, let's try to click the "Submit" button. When we are in the Spanish language, it will display the following screen:

Congratulations, there is now a multilingual web page that can start your website globally.

Articles you may be interested in:
  • Briefly describe how to use merge labels in Java Struts Framework
  • Summary of exception handling methods for Java Struts Framework
  • Detailed explanation of the use of stack values and OGNL In the Struts framework of Java
  • Implementation of the login function and the use of Form processor in the Struts framework of Java

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.