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)
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.
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.
You can write a PlayPlugin and trim all parameters of the request.
Another possibility is to use the Before-Interception.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With