It is best practice to have all the labels used in your application in the centralized location. Tradionally these message resources are stored in the property files using the key=value pairs and loaded on demand by the forms. Every framework supports this basic feature to configure the message resources. This example shows how to load property files in your Struts 2 Application and display it in the screen. Lets look at the code.
1. Action Class
package javabeat.net.struts2; public class Struts2HelloWorldAction{ private String firstName; private String lastName; public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String execute(){ return "success"; } }
2. Property File
Create a property file in the class path.
form_labels.properties
firstName=First Name lastName=Last Name
3. Struts 2 Configuration File
Add the entry for loading the property files from the class path.
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd"> <struts> <constant name="struts.custom.i18n.resources" value="form_labels" /> <constant name="struts.devMode" value="true" /> <package name="uitagsdemo" extends="struts-default"> <action name="PropertyDemo" class="javabeat.net.struts2.Struts2HelloWorldAction" > <result name="success">Input.jsp</result> </action> </package> </struts>
4. JSP File
Input.jsp
<%@ page contentType="text/html; charset=UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags"%> <html> <head> </head> <body> <h2>JavaBeat - Struts 2 Property Labels Demo</h2> <s:form action="PropertyDemo"> <s:textfield name="firstName" key="firstName" /> <s:textfield name="lastName" key="lastName" /> <s:submit label="Submit" /> </s:form> </body> </html>
5. Resource Bundle Demo
If you access the application using URL http://localhost:8080/Struts2App/PropertyDemo, you would see the following output.