Spring-mvc – Character encoding issue with Spring MVC and HTML form

character encodingformshttp-postspring-mvc

I'm working with spring mvc. I've set up a web form that has two simple text inputs. On controller, I use @ModelAttribute to let spring build the bean from the web form.

The problem comes when user puts on those text fields specials characters, like 酒店 and this kind of stuff, spring doesn't read it as utf-8, and they become the usual bad-encoded string.

I've checked web.xml and there's the utf-8 encoding filter, all pages are marqued as utf-8 and browser is sending right charset headers. Any idea on what's going on?

Best Answer

You may want to check this out: http://forum.springsource.org/showthread.php?81858-ResponseBody-and-UTF-8

The short of it is that if you are using annotated methods then the messageconverter being used has a default character set. You can change this setting in your web.xml by setting the supported media types.

However, if your service doesn't like that media type, you may get a 406 error. You can create your own string message converter and set the default encoding, but there is no easy way with the built in HttpStringMessageConverter.

Alternately you can re-encode a string to a different character set:

String newresponse = new String(responseString.getBytes("ISO-8859-1"), "UTF-8"); 

You may also want to check out the related question here: How to get UTF-8 working in Java webapps?

Related Topic