Tuesday, 3 December 2013

Struts2 Localize addActionMessage

Today i am sharing my demo example to read the properties file in struts action class.suppose you have a requirement to  show the localize message to UI like “Invalid username/password”[It can be in any language].

I am going to demonstrate the example step by step.

1. Create your default web project directory structure in your IDE.
2. Open the web.xml file and do filterdispatcher entry in it.

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
 <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>
 <welcome-file-list>
 <welcome-file>index.jsp</welcome-file>
 </welcome-file-list>
</web-app>
 
 3. Now create a struts.xml file in your src folder.

<!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" />
 <package name="struts2" extends="struts-default" namespace="/">
 <action name="displayActionMessage">
 <result name="success">/showaction.jsp</result>
 </action>
 </package>
</struts>

4. Create a properties file name “ShowAction.properties” within your package.

project.test.myvalue=Hello AOIblog

5.Now create a one Struts2 Action class named “ShowAction”.

package com.example.actions;
import com.opensymphony.xwork2.ActionSupport;
public class ShowAction extends ActionSupport {
 
 public String execute() {
 System.out.println("I m calling");
 addActionMessage(getText("project.test.myvalue"));
 return SUCCESS;
 }
}
 

6. Now create the one jsp file named “showaction.jsp”

<%@ 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>
 <meta http-equiv="Content-Type"
 content="text/html; charset=ISO-8859-1">
  <title>Localize Action Message from Struts2 Action</title>
 </head>
 <body>
 <s:actionmessage/>
 </body>
</html>

Now deploy your application and run the following URL at your browser
 http://localhost:8080/YourProjectName/displayActionMessage.action

If you have any problem in this example so please free feel to ask.
Thanks to visit.

No comments:

Post a Comment