Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Struts2 type conversion


May 15, 2021 Struts2



Everything on the HTTP request is treated as a string by protocol, including numbers, Boolean values, integers, dates, indges, and so on. F or HTTP, each event is a string. H owever, in the Struts class, you can have properties of any data type. How do we get Struts to automatically match properties?
Struts does a lot of hard work behind the scenes using various types of converters. F or example, if you have an integer property in your Action class and you don't need to do anything, Struts automatically converts the requested parameters to the integer property. B y default, Struts provides multiple types of converters. Some of them are listed below, and if you use one of them, you don't have to worry about anything:

  • Integer,Float,Double,Decimal

  • Date,Datetime

  • Arrays,Collections

  • Enumerations

  • Boolean

  • BigDecimal

Sometimes, when you use your own data types, it is necessary to add your own converters so that Struts knows how to convert these values before displaying them. Consider using the POJO class Environment .java.

package cn.w3cschool.struts2;

public class Environment {
   private String name;
   public  Environment(String name)
   {
      this.name = name;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
}

This is a very simple class, it has a name property, but there is nothing special about it. L et's next create another class that contains system information: SystemDetails .java. F or the purposes of the exercise, we are hard-coded the environment as "development" and the operating system as "Windows XP SP3". I n the actual project, you get this information from the system configuration. S o let's start by creating the following action class:

package cn.w3cschool.struts2;
import com.opensymphony.xwork2.ActionSupport;

public class SystemDetails extends ActionSupport {
   private Environment environment = new Environment("Development");
   private String operatingSystem = "Windows XP SP3";

   public String execute()
   {
      return SUCCESS;
   }
   public Environment getEnvironment() {
      return environment;
   }
   public void setEnvironment(Environment environment) {
      this.environment = environment;
   }
   public String getOperatingSystem() {
      return operatingSystem;
   }
   public void setOperatingSystem(String operatingSystem) {
      this.operatingSystem = operatingSystem;
   }
}

Let's then create a simple JSP file system .jsp display environment and operating system information.

<%@ 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>
<title>System Details</title>
</head>
<body>
   Environment: <s:property value="environment"/><br/>
   Operating System:<s:property value="operatingSystem"/>
</body>
</html>

Let's use the struts .xml to connect the system .jsp and SystemDetails .java classes. T he SystemDetails class has a simple execute() method that returns the string "SUCCESS".

<?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" />
   <package name="helloworld" extends="struts-default">
      <action name="system" 
            class="com.tutorialspoint.struts2.SystemDetails" 
            method="execute">
         <result name="success">/System.jsp</result>
      </action>
   </package>
</struts>

Now, right-click on the project name, and then click "Export" and "WAR File" to create a WAR file. T he WAR file is then deployed in Tomcat's webapps directory. Finally, start the Tomcat server and try to access the URL http://localhost:8080/HelloWorldStruts2/system.action display the following interface:

Struts2 type conversion

What's wrong with the output above? S truts knows how to display and transform Windows XP SP3 strings and other built-in data types, but it doesn't know how to handle Environment-type properties. S o, it simply uses the toString() method in the class upring. T o solve this problem, let's now create and register a simple TypeConverter for the Environment class. C reate a class called EnvironmentConverter .java that contains the following:

package cn.w3cschool.struts2;

import java.util.Map;
import org.apache.struts2.util.StrutsTypeConverter;

   public class EnvironmentConverter extends StrutsTypeConverter {
      @Override
      public Object convertFromString(Map context, String[] values, 
                                      Class clazz) {
      Environment env = new Environment(values[0]);
      return env;
   }

   @Override
   public String convertToString(Map context, Object value) {
      Environment env  = (Environment) value;
      return env == null ? null : env.getName();
   }	
}

EnvironmentConverter extends the StrutsTypeConverter class and tells Struts how to convert Environment to String by overwriting convertFromString() and convertToString(). N ow, let's register this converter in the application before we use it, and there are two ways to register the converter. If the converter will only be used in specific operations, then you must create a property file named 'action-class'-conversion.properties, so, in our case, create a file called SystemDetails-converstion.properties that contains the following registry:

environment=cn.w3cschool.struts2.EnvironmentConverter

In the example above, "environment" is the name of .java in the SystemDetails class to tell Struts to use EnvironmentConverter to convert the property. H owever, our approach will be the opposite, and we will register the converter globally so that it can be used throughout the application. T herefore, you need to create a property file called xwork-conversion.properties in the WEB-INF/classes folder, using the following:

cn.w3cschool.struts2.Environment = 
            cn.w3cschool.struts2.EnvironmentConverter

This simply registers the converter globally, allowing Struts to automate the transformation each time it encounters an object of type Environment. N ow, if you recompile and re-run the program, you'll get a better output, as follows:

Struts2 type conversion

Obviously, the results are better now, which means that our Struts converter is working properly. This is how to create multiple converters and register to use them according to your requirements.