Reputation: 103
After upgrading from Play! 2.4 to Play! 2.5 there seems to be a problem with form-enconding. German umlauts for example really get messed up. For example the german word "Bär" becomes "Bär". I already changed the way I access form data from
Form.form(Form.class).bindFromRequest();
to the injected way, as described in the migration guide:
formFactory.form(Form.class).bindFromRequest();
Is there a was to fix the character encoding in Play 2.5?
Upvotes: 2
Views: 948
Reputation: 4596
This is a bug in play 2.5 , see github issue: https://github.com/playframework/playframework/pull/5920
I resolve this with a custom body parser:
package com.kashi.ssff.services;
import akka.util.ByteString;
import play.api.http.HttpConfiguration;
import play.core.parsers.FormUrlEncodedParser;
import play.http.HttpErrorHandler;
import play.libs.F;
import play.libs.streams.Accumulator;
import play.mvc.BodyParser;
import play.mvc.BodyParsers;
import play.mvc.Http;
import play.mvc.Result;
import javax.inject.Inject;
import java.util.Map;
/**
* Created by mohsen on 3/21/16.
*/
public class FormBodyParser extends BodyParser.BufferingBodyParser<Map<String, String[]>> {
private final HttpErrorHandler errorHandler;
public FormBodyParser(long maxLength, HttpErrorHandler errorHandler) {
super(maxLength, errorHandler, "Error parsing form");
this.errorHandler = errorHandler;
}
@Inject
public FormBodyParser(HttpConfiguration httpConfiguration, HttpErrorHandler errorHandler) {
super(httpConfiguration, errorHandler, "Error parsing form");
this.errorHandler = errorHandler;
}
@Override
public Accumulator<ByteString, F.Either<Result, Map<String, String[]>>> apply(Http.RequestHeader request) {
return BodyParsers.validateContentType(errorHandler, request, "Expected application/x-www-form-urlencoded",
ct -> ct.equalsIgnoreCase("application/x-www-form-urlencoded"), super::apply);
}
@Override
protected Map<String, String[]> parse(Http.RequestHeader request, ByteString bytes) throws Exception {
String charset = request.charset().orElse("UTF-8");
return FormUrlEncodedParser.parseAsJavaArrayValues(bytes.decodeString(charset), charset);
}
}
and annotate controller with this body parser:
@BodyParser.Of(FormBodyParser.class)
public Result register() {
.
.
.
With special thanks @GregMethvin
Upvotes: 2
Reputation: 259
in your form try adding the accept-charset="ISO-8859-1"
<form accept-charset="ISO-8859-1" action="whatever" method="post">
tested it for the word Bär
and it works fine
EDIT:
For the arabic script the characters are stored as ISO-8859-1 encoded as well. An image to show that at the end all goes well.
Upvotes: 0