Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.
like image 822
ripper234 Avatar asked Nov 17 '11 13:11

ripper234


People also ask

Which annotation indicates class as controller?

The @Controller annotation indicates that a particular class serves the role of a controller.

What is the@ controller annotation used for?

The basic purpose of the @Controller annotation is to act as a stereotype for the annotated class, indicating its role. The dispatcher will scan such annotated classes for mapped methods, detecting @RequestMapping annotations (see the next section).

Which of these annotations can be applied on spring MVC controller method parameters?

Spring 2.5 introduced an annotation-based programming model for MVC controllers that uses annotations such as @RequestMapping , @RequestParam , @ModelAttribute , and so on. This annotation support is available for both Servlet MVC and Portlet MVC.


2 Answers

You do this in the routes file:

POST /person/add   MyController.addPerson

There is more documentation on this here.

like image 58
Rich Avatar answered Sep 29 '22 08:09

Rich


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...
    }
}
like image 26
kritzikratzi Avatar answered Sep 29 '22 08:09

kritzikratzi