ripper234
ripper234

Reputation: 230156

Can I mark a controller method as POST in Play using annotations?

I didn't find this anywhere - can i tell Play! that a specific controller method should (only) be accessed via HTTP POST?

Something like the HttpPost attribute in C#'s Asp.Net MVC?

public class MyController extends Controller {

  @Post
  public void addPerson(String name, String address) {
  }
}

Update - I don't understand what adding a POST route do:

  1. A POST request will work without adding such a route.
  2. Because the method is still catched by the "Catch all" GET rule, even adding the POST route won't prevent GET requests to this method.

Upvotes: 5

Views: 1091

Answers (3)

kritzikratzi
kritzikratzi

Reputation: 20231

i'm a little late to the party. afaik there's no built in annotation, but you can quite easily write one yourself:

annotations/HttpMethod.java

/**
 * Add this annotation to your controller actions to force a get/post request. 
 * This is checked in globals.java, so ensure you also have @With(Global.class) 
 * in your controller
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface HttpMethod{
    String method() default "POST";
}

controllers/Global.java

/**
 * All the funky global stuff ... 
 */
public class Global extends Controller{

    @Before
    public static void before(){
        if( getActionAnnotation( HttpMethod.class ) != null ){
            HttpMethod method = getActionAnnotation( HttpMethod.class ); 
            if( !method.method().equals( request.method ) ){
                error( "Don't be evil! " ); 
            }
        }
    }
}

usage: controllers/Admin.java

@With({Global.class, Secure.class})
public class Admin extends Controller {
    @HttpMethod(method="POST")
    public static void save( MyModel model ){
        // yey...
    }
}

Upvotes: 2

Marius Soutier
Marius Soutier

Reputation: 11274

You could do it this way:

public static void onlyPost() {
  if (request.method.equals("POST")) {
     // ... Do stuff
     render(); 
  }
  else
    forbidden();
}

But keep in mind that your code and your routes file might be out of sync.

Also, you can use Groovy code inside the routes file, so no need for duplication.

# Catch all
#{if play.mode.isDev()}
*   /{controller}/{action}       {controller}.{action}
#{/if}

Upvotes: 1

Rich
Rich

Reputation: 15767

You do this in the routes file:

POST /person/add   MyController.addPerson

There is more documentation on this here.

Upvotes: 2

Related Questions