Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trim request parameters automatically in playframework

Play will assign the parameters from request to action parameters, like:

public static void createArticle(String title, String content) {
}

But it won't trim them, so we usually to such code in the actions:

public static void createArticle(String title, String content) {
    if(title!=null) title = title.trim();
    if(content!=null) content = content.trim();
}

Is there any way to let play trim them automatically?

like image 916
Freewind Avatar asked Jun 30 '11 09:06

Freewind


3 Answers

There are multiple ways to achive this with custom binders. One way of doing would be this:

  • Define acustom binder somewhere that trims the string
  • Annotate every parameter you want to trim with @As(binder=TrimmedString.class)

    public class Application extends Controller {
    
        public static class TrimmedString implements TypeBinder<String> {
            @Override
            public Object bind(String name, Annotation[] annotations, String value, Class actualClass, Type genericType) throws Exception {
                if(value != null) {
                    value = value.trim();
                }
                return value;
            }
        }
    
        public static void index(
                @As(binder=TrimmedString.class) String s1,
                @As(binder=TrimmedString.class) String s2,
                @As(binder=TrimmedString.class) String s3) {
            render(s1, s2, s3);
        }
    }
    

If this is too verbose for you, simply use a @Global binder for String which checks for a custom @Trim or @As('trimmed') annotation. The TypeBinder already has all annotations available so this should be very easy to implement.

All this can be found in the documentation under custom binding.

like image 110
Florian Gutmann Avatar answered Nov 28 '22 09:11

Florian Gutmann


A simple way to do it would be to use object mappings instead, of individual String mappings.

So, you could create a class call Article, and create a setter that trims the content. Normally Play doesn't need you to create the setters, and they are autogenerated behind the scenes, but you can still use them if you have special processing.

public class Article {
    public String title;
    public String content;

    public void setTitle(String title) {
         this.title = title.trim();
    } 
    public void setContent(String content) {
         this.content = content.trim();
    }
}

You then need to pass the Article into your action method, rather than the individual String elements, and your attributes will be trimmed as part of the object mapping process.

like image 37
Codemwnci Avatar answered Nov 28 '22 07:11

Codemwnci


You can write a PlayPlugin and trim all parameters of the request.

Another possibility is to use the Before-Interception.

like image 38
niels Avatar answered Nov 28 '22 07:11

niels