Pregunta

In grails we can define an action using 2 ways:-

def actionname()
{

}

and

def actionname = {

}

What is the difference between the two styles? When I tried to insert a spring security annotation above the action (second style) it said "@Secured" not applicable to field. What does this mean? Is it because of closure?

¿Fue útil?

Solución

The Grails reference docs 7.The Web Layer mentions the use of closures for controller actions in earlier versions of Grails, the preference is now to use methods. However, both are supported. It goes on to list some benefits of using methods instead.

Personally, I use methods in all my controllers and have also come across the issue with annotations such as @Secured that only work on methods and not the closures.

Otros consejos

In earlier versions of Grails option 2 (actions as closures) was the only supported style. Grails 2.x introduced the actions-as-methods style and this is now the recommended approach, but the closure style is still supported for backwards compatibility and you'll see it if you are working on an app (or plugin) that was originally written on Grails 1.x.

The first is normal method definition with undefined return type.

The second is an assigment of a closure to a property 'actionname'.

That is why you get "@Secured" not applicable to field message, because this annotation is for methods only.

Shuttsy is correct that that the first way is now a preffered way to define actions in Grails.

  1. This is an agreeable way of defining methods in Groovy at minimal level having the structure above.

  2. The second way of defining is not refering to a method definition rather it's somehow a rule like closure constraints that governs a given class or method. Like when it is used in domain class .

Example

    class Person {
    String name
    Person parent
    static belongsTo = [ supervisor: Person ]

    static mappedBy = [ supervisor: "none", parent: "none" ]

    static constraints = { supervisor nullable: true }

    //this allowed for methods only and why you got an error in above cases
    @override
    def toString(){
       return name.toString()
     } 
}

@Secured annotation accept list of roles (String[]) it is used only for a method definition based on toString() method inside the class ...i just give u a scenario of the two ..

@Secured annotation since spring security 2.0 supports method only. As a result, you have to convert closures to real methods if you want to apply the security annotation for it. Read more @Secured Annotation.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top