Corey
Corey

Reputation: 1133

Save Chinese characters with Spring-MVC / Java

I'm trying to save Chinese characters from a form submit into the database.

I've set the contentType on the jsp via

<%@ page contentType="text/html;charset=UTF-8" %>

I've also set this tag inside the of the jsp:

<META HTTP-EQUIV="content-type" CONTENT="text/html; charset=UTF-8" />

However, when I submit the form, my controller sees a different character than what I entered.

I am entering the character 我 and seeing æ?? in the controller. When the data redisplays on the page, it shows the same wrong character (æ??).

Why isn't the controller getting the correct character?

Upvotes: 1

Views: 3739

Answers (3)

Enrique
Enrique

Reputation: 10117

Declare a CharacterEncodingFilter in your web.xml file before any other filter

<filter>
    <filter-name>charsetFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
</filter>

<filter-mapping>
    <filter-name>charsetFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

In your jsp file try adding this at the very start of the file:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>

Upvotes: 3

Jacob Mattison
Jacob Mattison

Reputation: 51052

Not all browsers will respect the character set you've specified in the page or the form. Spring provides a filter, the CharacterEncodingFilter, that can add a character encoding or force a particular encoding, as the request comes in and before it hits the controller.

Upvotes: 1

Jan Thom&#228;
Jan Thom&#228;

Reputation: 13604

Add an accept-charset attribute to your form:

<form method="POST" accept-charset="utf-8" ... >

This tells the browser to submit your form contents as UTF-8 to the server.

Upvotes: 0

Related Questions