How concatenate two string in Spring Expression Language (SpEL)
Asked Answered
O

3

9

In my spring application, the methods from my controller and service classes have this annotation to security purposes:

@PreAuthorize("hasPermission(#user, 'cadastra')")

the second argument, the permission, should have this format:

<<action_name>>_<<class_name>>

What expression I should use to accomplish that, taking in consideration the class name is held by this.getClass().getName()?

Otes answered 9/6, 2014 at 13:23 Comment(4)
Do you mean this doesn't work: @PreAuthorize("hasPermission(#user, 'cadastra_' + this.class.name)")?Alpenstock
I try exactly this way and don't work. Before this, I also try use: @PreAuthorize("hasPermission(#user, 'cadastra_#this.class.name')")unsuccessfully.Otes
A combination of those two suggestions perhaps: @PreAuthorize("hasPermission(#user,'cadastra_'+#this.class.name)")Defazio
yes, I try this too, but I got access denied in all cases. Is there any way to verify which the final value for this string is receiving?Otes
O
3

I finally solve this. I add a new method in my controller:

public String getName() {
    String nome_classe = entityClass.getSimpleName();
    System.out.println("getName nome_class = "+nome_classe);
    return nome_classe;
}

and now I use the annotation in that way:

@PreAuthorize("hasPermission(#user, 'cadastra_'+#this.this.name)")
Otes answered 19/6, 2014 at 13:48 Comment(0)
I
18

To concatenate two strings in Spring EL you use concat function . See here for more details : Spring EL docs

for example, I used the following :

    @PreAuthorize("hasRole('ROLE_'.concat(this.class.simpleName))")
Imperforate answered 17/6, 2014 at 22:35 Comment(0)
O
3

I finally solve this. I add a new method in my controller:

public String getName() {
    String nome_classe = entityClass.getSimpleName();
    System.out.println("getName nome_class = "+nome_classe);
    return nome_classe;
}

and now I use the annotation in that way:

@PreAuthorize("hasPermission(#user, 'cadastra_'+#this.this.name)")
Otes answered 19/6, 2014 at 13:48 Comment(0)
B
0

If one of the strings is a variable, you can do this:

EvaluationContext ctx = new StandardEvaluationContext();
ctx.setVariable("lat", 30.3);
ctx.setVariable("lng", 110.00);
// https://docs.spring.io/spring-framework/docs/3.2.x/spring-framework-reference/html/expressions.html#expressions-ref-variables
String loc = ep.parseExpression("'{\"lng\":'.concat(#lng).concat(',\"lat\":').concat(#lat).concat('}')").getValue(ctx, String.class);

the result is:

{"lng":110.0,"lat":30.3}
Boudicca answered 12/1 at 4:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.