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?
There are multiple ways to achive this with custom binders. One way of doing would be this:
Annotate every parameter you want to trim with
@As(binder=TrimmedString.class)
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.
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.
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.
You can write a PlayPlugin and trim all parameters of the request.
Another possibility is to use the Before-Interception.