Struts 2 + REST Web Service Integration Example

By Arvind Rai, January 04, 2015
This page will provide the Struts 2 and REST web service integration example. Struts 2 provide REST plugin to implement REST web service. Parent package should be rest-default. Conventionally action class name is written with Controller suffix. Struts 2 REST web service supports different content-type response. To get response as JSON, use json extension and to get XML response, use xml extension. In the example we have an employee repository REST web service. For the given employee id in REST URL, employee profile is retuned by the application.

Required Software to Run Application

To run the example, we need below software.
1. Java 7
2. Tomcat 7
3. Eclipse
4. Maven

Project Structure in Eclipse

Find the project structure in eclipse for struts 2 and REST web service integration.
Struts 2 + REST Web Service Integration Example

pom.xml: Struts 2 REST Plugin

To resolve struts 2 REST API, we need the below plugin in our pom.xml
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.concretepage</groupId>
  <artifactId>struts2rest</artifactId>
  <packaging>war</packaging>
  <version>1</version>
  <name>Struts2Rest</name>
  <dependencies>
	<dependency>
		<groupId>org.apache.struts</groupId>
		<artifactId>struts2-convention-plugin</artifactId>
		<version>2.3.20</version>
	</dependency>
	<dependency>
		<groupId>org.apache.struts</groupId>
		<artifactId>struts2-rest-plugin</artifactId>
		<version>2.3.20</version>
	</dependency>
  </dependencies>
</project> 
To support struts 2 rest plugin, we need to resolve dependency for struts 2 convention plugin.

struts.xml : Configure Convention Plugin

Find the struts.xml in which struts convention plugin is configured.
struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
	"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
    <constant name="struts.convention.action.suffix" value="Controller"/>
    <constant name="struts.convention.action.mapAllMatches" value="true"/>
    <constant name="struts.convention.default.parent.package" value="rest-default"/>
    <constant name="struts.convention.package.locators" value="rest"/>
</struts> 
Find the description for the convention plugin being used.

<constant name="struts.convention.action.suffix" value="Controller"/>: Defines a suffix for action class. Conventionally action class for REST web service has Controller suffix and this suffix will not be included in URL.

<constant name="struts.convention.action.mapAllMatches" value="true"/>: mapAllMatches can be true or false.

<constant name="struts.convention.default.parent.package" value="rest-default"/>: To support REST web service, struts 2 uses rest-default as parent package.

<constant name="struts.convention.package.locators" value="rest"/>: Locator is the last word of the package within which controller action class resides. In our class, it is rest.

Create Employee Repository

For the demo application, we are creating an employee repository. First find the employee class.
Employee.java
package com.concretepage.rest;
public class Employee {
	private Integer id;
	private String name;
	private String company;
	public Employee(Integer id, String name, String company){
		this.id =id;
		this.name = name;
		this.company = company;
	}
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getCompany() {
		return company;
	}
	public void setCompany(String company) {
		this.company = company;
	}
} 
Now find the repository class with some sample data.
EmployeeRepository.java
package com.concretepage.rest;
import java.util.HashMap;
import java.util.Map;
public class EmployeeRepository {
	private static Map<String,Employee> map = new HashMap<String,Employee>(); 
	public EmployeeRepository(){
		map.put("111", new Employee(111, "Ram", "ABC"));
		map.put("222", new Employee(222, "Shyam", "EFG"));
		map.put("333", new Employee(333, "Mohan", "XYZ"));
	}
	public  Employee getEmployeeById(String id){
		return map.get(id);
	}
	public  Map<String,Employee> findAllEmployee(){
		return map;
	}
} 

Create Controller Action Class: Implement ModelDriven

Find the controller class. The class will extend ModelDriven and need to override getModel () method. Whenever a REST URL is hit, this is the method which returns response.
EmployeeController.java
package com.concretepage.rest;
import java.util.Map;
import org.apache.struts2.rest.DefaultHttpHeaders;
import org.apache.struts2.rest.HttpHeaders;
import com.opensymphony.xwork2.ModelDriven;
public class EmployeeController implements ModelDriven<Object>{
	private static final long serialVersionUID = 1L;
	private String id;
	private Object model;
	private EmployeeRepository employeeRepository = new EmployeeRepository();
	private static Map<String,Employee> map;
	{
		map = employeeRepository.findAllEmployee();
	}
	public HttpHeaders index() {
		model = map;
		return new DefaultHttpHeaders("index").disableCaching();
	}
	public String add(){
		Integer empId = Integer.parseInt(id);
		Employee emp = new Employee(empId,"Ramesh", "PQR");
		model = emp;
		return "SUCCESS";
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		model = employeeRepository.getEmployeeById(id);
		this.id = id;
	}
	@Override
	public Object getModel() {
		return model;
	}
}   
1. URL for index(): The REST web service URL can be as below for the index() method.

http://localhost:8080/struts2rest-1/employee.json
http://localhost:8080/struts2rest-1/employee.xml

Look at the URL. employee has been taken from EmployeeController class. Suffix is ignored. The default method is index(). To fetch JSON response, use json extension and to fetch xml response, use xml extension.

2. URL for id: Now find other URLs for id setter and getter.

http://localhost:8080/struts2rest-1/employee/111.json
http://localhost:8080/struts2rest-1/employee/111.xml

To pass any input value, there must an id property and we need to create setter and getter method for the id.

3. URL for add(): To call our own method, create a method like add(). This method will be called after id setter and getter. The value 555 in the URL will be assigned to id. The URL will be as below.

http://localhost:8080/struts2rest-1/employee/555/add.json
http://localhost:8080/struts2rest-1/employee/555/add.xml

This url will call add() method and return data assigned to model.

web.xml for Application

Find the web.xml for struts 2.
web.xml
<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
  <display-name>Struts 2 REST Web Service</display-name>
   <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
        <init-param>
            <param-name>actionPackages</param-name>
            <param-value>com.concretepage.action</param-value>
        </init-param>
    </filter>
  <filter-mapping>
	<filter-name>struts2</filter-name>
	<url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app> 

Output

1. JSON Response of the URL http://localhost:8080/struts2rest-1/employee/111.json
{"company":"ABC","id":111,"name":"Ram"} 
XML response of the URL http://localhost:8080/struts2rest-1/employee/111.xml
<com.concretepage.rest.Employee>
<id>111</id>
<name>Ram</name>
<company>ABC</company>
</com.concretepage.rest.Employee> 
Find the screenshot.
Struts 2 + REST Web Service Integration Example
2. JSON Response of the URL http://localhost:8080/struts2rest-1/employee/555/add.json
{"company":"PQR","id":555,"name":"Ramesh"} 
XML response of the URL http://localhost:8080/struts2rest-1/employee/555/add.xml
<com.concretepage.rest.Employee>
<id>555</id>
<name>Ramesh</name>
<company>PQR</company>
</com.concretepage.rest.Employee>
Find the screenshot.
Struts 2 + REST Web Service Integration Example
Now we are done. Happy Learning.

Reference

REST Plugin

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us