Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Struts 2 Type Conversion
3.
Frequently Asked Questions
3.1.
What is collection and map support?
3.2.
What is the need for type conversion in struts 2?
3.3.
How can we apply a type converter globally?
3.4.
What is advanced type conversion?
4.
Conclusion
Last Updated: Mar 27, 2024
Medium

Struts 2 Type Conversion

Introduction

This article shows you how to perform Struts 2 Type Conversion. Though for the data types like boolean, character, integer, arrays, and other fundamental types already defined in language, struts automatically auto wires the arguments with the help of its variety of type converters. But we should have knowledge of struts 2 type conversion as we may need to create our own type converters for user-defined arguments or types.

Struts 2 type conversion

Struts 2 Type Conversion

Be it any data type, numbers, booleans, dates, integers, decimals, or anything else, all these types are treated as strings in HTTP requests which makes it very important for the strut to have type conversion while using these data types. So let's see how the struts use its variety of type converters to do this struts 2 type conversion.

Struts automatically change the request type to its original type without your intervention if your action class contains a type among the fundamental types already defined. Struts have a variety of type converters by default.

These fundamental types about which we shouldn't worry include:

  • Integer, Float, Double, Decimal
  • Arrays and Collections
  • Date and Datetime
  • Boolean
  • BigDecimal
  • Enumerations

But we should be careful while using our own data types because it may be required to include your own converters when using your own data type so that Struts knows how to transform the values before displaying them.

User defined types vs fundamental types

 

Below is an example to demonstrate struts 2 type conversion:

Look at POJO class Env.java

package com.Coding Ninjas Studio.struts2;
public class Env {
   private String name;  
   public  Env(String name) {
      this.name = name;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
}

 

Let's make SysD.java, a new class that includes details about the system.

You would obtain this information from the system settings in a real-time project.

Let's create the following action class:-

package com.Coding Ninjas Studio.struts2;
import com.opensymphony.xwork2.ActionSupport;

public class SysD extends ActionSupport {
   private Env environment = new Env("Development");
   private String operatingSystem = "Windows XP SP3";
   public String execute() {
      return SUCCESS;
   }
   public Env getEnvironment() {
      return environment;
   }
   public void setEnvironment(Env environment) {
      this.environment = environment;
   }
   public String getOperatingSystem() {
      return operatingSystem;
   }
   public void setOperatingSystem(String operatingSystem) {
      this.operatingSystem = operatingSystem;
   }
}

 

Let's next construct a straightforward JSP file system. jsp to show information about the operating system and the environment.

 

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

 

Type coversion

 

Let's use struts.xml to connect the system.jsp and the SysD.java class.

<?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.Coding Ninjas Studio.struts2.SysD" 
            method = "execute">
         <result name = "success">/System.jsp</result>
      </action>
   </package>
</struts>

 

Struts can display and convert other built-in data types, such as the string "Windows XP SP3," but it cannot handle the Environment type's property. In the class, it is called the function toString() method.

Let's now develop and register a basic TypeConverter for the Env class to address this issue.

The following code should be placed in a class called EnvConverter.java.

package com.Coding Ninjas Studio.struts2;

import java.util.Map;
import org.apache.struts2.util.StrutsTypeConverter;
public class EnvConverter extends StrutsTypeConverter {
   @Override
   public Object convertFromString(Map context, String[] values, Class clazz) {
      Env e = new Env(values[0]);
      return e;
   }
   @Override
   public String convertToString(Map context, Object value) {
      Env e  = (Env) value;
      return e == null ? null : e.getName();
   }
}
Type convertors in struts 2

 

By overriding two methods, convertFromString() and convertToString(), the EnvConverter class extends the StrutsTypeConverter class and instructs Struts on how to convert Environment to a String and vice versa ().


It is necessary to generate a property file with the name "[action-class]converstion.properties" if the converter will only be utilized in that action.

In our instance, the following registry entry is created in a file called SysD-converstion.properties:-

environment = com.Coding Ninjas Studio.struts2.EnvConverter

 

In the example mentioned above, we are instructing Struts to use the EnvConverter to convert to and from the property with the name "environment" found in the SysD.java class.

com.Coding Ninjas Studio.struts2.Env = \
   com.Coding Ninjas Studio.struts2.EnvConverter

 

By registering the converter globally, Struts can do the conversion whenever it comes across an object of the Environment type.

Congratulations, you have learned how to apply struts 2 type conversion by creating your own type converters.

Let's not forget to have sight of the frequently asked questions.

Frequently Asked Questions

What is collection and map support?

For Java Collections, collection and map support provide intelligent null handling and type conversion. The framework provides methods for identifying the object type of collection element. An ObjectTypeDeterminer is utilized to make the discovery. The framework comes with a default implementation.

What is the need for type conversion in struts 2?

The protocol handles every element of an HTTP request as a String; therefore, it is necessary to convert the element types to convert them into their original forms for the proper execution of desired operations.

How can we apply a type converter globally?

A type converter can be used globally. This can be done by editing the file struts-conversion.properties or xwork-conversion.properties in the root of your classpath and adding a property in the form of the class names of the type converter and the object you wish to convert on the left and right, respectively.

What is advanced type conversion?

The handling of null properties, converting values in Maps and Collections, and type conversion error handling are all advanced type conversion cases handled by Struts 2.

Conclusion

This article taught us about struts 2 type conversion and where we need type conversions. We saw some fine examples demonstrating struts 2 type conversion using type converters.

After exploring Struts 2 type conversion, are you not feeling excited to read/explore more articles on the topic of Java? Don't worry; Coding Ninjas has you covered. To learn, see Java Vs. Ruby, Java AWT Basics, and Java Keylistener.

Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSystem Design, and many more! 

Do upvote our blogs if you find them helpful and engaging!

Happy learning!

Live masterclass