Custom Type Converter in Struts2

Custom Type Converter in Struts2

In Struts2, type conversion is the process of converting form input data (typically strings) into appropriate Java types for action properties. Struts2 provides built-in type converters for common types (e.g., converting strings to integers or dates). However, there are scenarios where you need to convert data into custom types. For such cases, Struts2 allows developers to create custom type converters.

Custom Type Converter in Struts2

Benefits of Custom Type Converters:

  • 1.  Reusability : Once defined, a custom type converter can be reused across different actions and forms.
  • 2.  Separation of Concerns : Keeps type conversion logic separate from action logic, leading to cleaner code.
  • 3.  Flexibility : Handles complex conversion logic which might not be covered by default converters.

Java Example

Let’s create a custom type converter for a Person object which includes a name and age fields.

Step 1: Create the Person Class
java
package com.example.model;

public class Person {
    private String name;
    private int age;

    // Constructors, getters, and setters
    public Person() {}

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    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;
    }
}

Step 2: Create the Custom Type Converter
java
package com.example.converter;

import com.example.model.Person;
import org.apache.struts2.util.StrutsTypeConverter;

import java.util.Map;

public class PersonTypeConverter extends StrutsTypeConverter {

    @Override
    public Object convertFromString(Map context, String[] values, Class toClass) {
        if (values != null && values.length > 0) {
            String[] personData = values[0].split(",");
            if (personData.length == 2) {
                try {
                    String name = personData[0].trim();
                    int age = Integer.parseInt(personData[1].trim());
                    return new Person(name, age);
                } catch (NumberFormatException e) {
                    // Handle conversion error
                }
            }
        }
        return null;
    }

    @Override
    public String convertToString(Map context, Object object) {
        if (object instanceof Person) {
            Person person = (Person) object;
            return person.getName() + ", " + person.getAge();
        }
        return null;
    }
}

Step 3: Register the Custom Type Converter
properties
com.example.model.Person=com.example.converter.PersonTypeConverter


Place this file in the src/main/resources directory.

Step 4: Create Struts2 Action
java
package com.example.action;

import com.example.model.Person;
import com.opensymphony.xwork2.ActionSupport;

public class PersonAction extends ActionSupport {
    private Person person;

    @Override
    public String execute() {
        // Business logic with the converted person object
        return SUCCESS;
    }

    public Person getPerson() {
        return person;
    }

    public void setPerson(Person person) {
        this.person = person;
    }
}

Step 5: Create JSP Page
jsp
<%@ taglib uri="/struts-tags" prefix="s" %>
<html>
<head>
    <title>Person Form</title>
</head>
<body>
    <s:form action="person" method="post">
        <s:textfield name="person" label="Person (name,age)" />
        <s:submit value="Submit" />
    </s:form>
</body>
</html>


 struts.xml 

xml
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
    <package name="default" namespace="/" extends="struts-default">
        <action name="person" class="com.example.action.PersonAction">
            <result name="success">/personForm.jsp</result>
        </action>
    </package>
</struts>

Explanation of the Example

  • 1.  Person Class : A simple model class representing a person with name and age fields.
  • 2.  PersonTypeConverter : A custom type converter that converts a string in the format “name,age” into a Person object and vice versa.
  • 3.  xwork-conversion.properties : Registers the custom type converter for the Person class.
  • 4.  PersonAction : An action class that uses the Person object.
  • 5.  JSP Page : A form that takes input in the format “name,age” and submits it to the PersonAction.