Is it possible to mark a controller method as POST in Play using annotations?

I have not found it anywhere - can I say Play! what specific controller method should (only) be available via HTTP POST?

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

public class MyController extends Controller {

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

Refresh . I don't understand what adding a POST route does:

  • The POST request will work without adding such a route.
  • Since the method is still captured by the GET catch-all rule, even adding a POST route will not prevent GET requests to this method.
+5
source share
3 answers

You can do it as follows:

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

, .

, Groovy , .

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

:

POST /person/add   MyController.addPerson

.

+2

I'm a little late to the party. afaik there is no built-in annotation, but you can easily write one:

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! " ); 
            }
        }
    }
}

use: Controllers /Admin.java

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

All Articles