Search code examples
reststruts2struts

REST API with Struts


I'm trying to add a REST API to an existing struts 2 application.

The idea is to have part of the application using standard struts mapping, and another part using REST.

So I used the struts2-rest-plugin plugin, and added the following configuration:

struts.xml:

<constant name="rest" value="org.apache.struts2.rest.RestActionMapper"/>
<constant name="struts.mapper.class"   
  value="org.apache.struts2.dispatcher.mapper.PrefixBasedActionMapper"/>
<constant name="struts.mapper.prefixMapping" value="/rest:rest,/:struts"/>

struts.properties:

struts.action.extension=,htm,action,xml,json

TasksController.java:

package xxx.common.webservice.rest;

public class TasksController implements ModelDriven<Task> {

  public String update() {
    return "UPDATE";
  }

  // Handles /tasks/{id} GET requests
  public String show() {
    return "YES";
  }

  @Override
  public Task getModel() {
    // TODO Auto-generated method stub
    return null;
  }

}

With this configuration, the basic struts action work, but I can't get the REST actions to work. I also tried different struts.xml configurations (including the convention plugin options), but without any success, the mappings are never shown with the config-brower plugin.

Any idea of what I have missed or done wrong?


Solution

  • It finally worked, but it was a while ago and I don't remember exactly what I did, here is my configuration, hope this helps.

    struts.xml

    <constant name="struts.convention.action.mapAllMatches" value="true"/>
    <constant name="struts.convention.package.locators" value="webservice"/>
    <constant name="struts.convention.action.suffix" value="Controller"/>
    <constant name="struts.convention.default.parent.package" value="rest-default"/>
    
    
    <constant name="struts.mapper.class" value="org.apache.struts2.dispatcher.mapper.PrefixBasedActionMapper" />
    <constant name="struts.mapper.prefixMapping" value="/rest:rest,:struts" />
    
    <package name="home" namespace="/" extends="struts-default">
        ...
    </package>
    

    TaskController.java

    package com.test.webservice.rest;
    
    public class TaskController extends RestActionSupport implements
        ModelDriven<TaskDTO> {
          public final HttpHeaderResult show() {
             ...
          }
        ...
    }